【问题标题】:Set an 'int' in one event and use it in another event在一个事件中设置一个“int”并在另一个事件中使用它
【发布时间】:2015-11-08 16:27:02
【问题描述】:

我正在 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
 }
}

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

【问题讨论】:

  • 将yes 定义为全局变量。外部方法

标签: c# visual-studio if-statement int


【解决方案1】:

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

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
 }
}

【讨论】:

  • 谢谢!这对我的所有项目都有很大帮助:)
【解决方案2】:

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

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
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多