在一个事件中设置一个 'int' 并在另一个事件中使用它

Set an 'int' in one event and use it in another event

我正在 Windows 表单中制作一些东西 (C# Visual Studio) 但是我需要知道如何设置一个 int 然后在另一个事件中使用它。例如:

private void BtnYes_Click(object sender, EventArgs e)
{
    int yes = 1;
    int no = 0;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e) 
 {
    if (yes == 1) {
        //EVENT
 }
}

当我这样做时,我遇到了一些错误。谁能帮我这个?或者只是告诉我如何使用不同的技术来做这样的事情?

你需要为此使用一个字段:

private int _yes;
private void BtnYes_Click(object sender, EventArgs e)
{
    _yes = 1;
    int no = 0;
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e) 
 {
    if (_yes == 1) {
        //EVENT
 }
}

您声明的变量"yes"仅在方法范围内可见。通过使其成为 class 的字段,这将使它对 class 中的所有方法可见(私有时)。

class YourClass
{
    private int yes = 1;
    private int no = 0;

    private void BtnYes_Click(object sender, EventArgs e)
    {
        //Remove the type declaration here to use the class field instead. If you leave the type declaration, the variable here will be used instead of the class field.
        yes = 1;
        no = 0;

        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e) 
    {
        if (yes == 1) {
        //EVENT
        }
    }
}