我正在制作一个Windows窗体应用程序,我希望能够在按钮按下时用列表中的随机变量显示一个消息框。我创建了一个名为SetRandomCode的类来设置列表,并且希望为变量'testVariable'设置一个随机数。我是相当新的C#,所以我可能要对这个完全错误的方式,但这里是我的代码:从c#中按钮列表中选择一个随机变量#
SetRandomCode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication2
{
public class SetRandomCode
{
List<string> randomCodes = new List<string>();
public void setCode()
{
Random r = new Random();
int index = r.Next(randomCodes.Count);
string testVariable = randomCodes[index];
randomCodes.Add("Test");
randomCodes.Add("Test 2");
randomCodes.Add("Test 3");
}
}
}
Form1.cs的
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(testVariable);
}
}
}
我得到的错误是'名称'testVariable'在当前上下文中不存在。
任何帮助,将不胜感激:)
你的'testVariable'在'setCode'的范围内声明,并且只能在那里使用。 – Jim
另外,看着你的代码,你从'randomCodes'通过'string testVariable = randomCodes [index];'得到一个值,但是你在下一行填充列表。您想先填充列表,然后从中选择值。 – rbm