如何在事件处理程序内部使用值.c#

本文关键字:内部 程序 事件处理 | 更新日期: 2023-09-27 18:25:51

好的,所以我制作了一个表单,这是一个似乎不适合我的代码。我希望能够在button_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.
}

如何在事件处理程序内部使用值.c#

如果您不想将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内部完全可见。

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());
    }
}