好的,所以我制作了一个表单,这个代码似乎对我不起作用。我希望能够在button1_click的事件处理程序中使用int变量“guess”。我知道可能有一些非常简单的答案,但我找不到它。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Random rnd = new Random();
int guess = rnd.Next(1, 100);
}
public void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Convert.ToString(Form1.guess));
}//It says that I can't use this value because it hasnt been created
//but if I create it, then it gives me a random number each time the button is clicked.
}
答案 0 :(得分:3)
public partial class Form1 : Form
{
private int Guess {get; set;} //<-----declare in a visible scope
public Form1()
{
InitializeComponent();
Random rnd = new Random();
guess = rnd.Next(1, 100); //<------this only happens once, make sure you change when and where needed.
//Which would mean that that your Random object should also be moved outside the Form1() Constructor.
}
public void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Guess.ToString());
}
}
答案 1 :(得分:3)
如果您不希望将guess
提升为类级别字段,则另一个选择是对事件处理程序使用lambda表达式,如下所示:
public Form1()
{
InitializeComponent();
Random rnd = new Random();
int guess = rnd.Next(1, 100);
button1.Click += (s, e) =>
{
MessageBox.Show(Convert.ToString(guess));
};
}
变量guess
在lambda中完全可见。