名称';EachVar';在当前上下文中不存在

本文关键字:上下文 不存在 EachVar 名称 | 更新日期: 2023-09-27 18:25:42

我在输入变量的按钮中成功创建了一个int变量。但每次我试图将该变量插入另一个对象(在这种情况下是另一个按钮)时,我都会得到"当前上下文中不存在名称‘EachVar’"

代码:

     private void Set1_Click(object sender, EventArgs e)
    {
        if (PAT.Text != "" && Loading1.Value != 100 && Loading1.Value - 100 <= 0)
        {
        int EachVar = Convert.ToInt32(PAT.Text); //The Var 'EachVar'
        label1.Text = "Value: " + Convert.ToString(EachVar);
        }
    }

    private void Start_Click(object sender, EventArgs e)
    {
        if (Loading1.Value + EachVar < 100) // The Error
        {
            Timer1.Start();
            Timer1.Interval = 1000;
        }
        else
        {
            Loading1.Value = 100;
            Timer1.Stop();
        }
    }

名称';EachVar';在当前上下文中不存在

在编写代码时,变量将仅在{}范围内定义/存在,即方法Set1_Click()

你想在它之外定义它,这样它就可以用两种方法访问:

// Now it can be accessed throughout the class. 
// Note that I've called it "_eachVar" to follow the naming convention for 
// fields in a class. 
private int _eachVar = 0; 
private void Set1_Click(object sender, EventArgs e)
{
    if (PAT.Text != "" && Loading1.Value != 100 && Loading1.Value - 100 <= 0)
    {
    _eachVar = Convert.ToInt32(PAT.Text); //The Var 'EachVar'
    label1.Text = "Value: " + Convert.ToString(EachVar);
    }
}

private void Start_Click(object sender, EventArgs e)
{
    if (Loading1.Value + _eachVar < 100) // The Error
    {
        Timer1.Start();
        Timer1.Interval = 1000;
    }
    else
    {
        Loading1.Value = 100;
        Timer1.Stop();
    }
}

还要注意,您可能使用了一个隐藏后台字段的属性。。

private int EachVar
{
    get { return _eachVar; }
    set { _eachVar = value; }
}

或者一个自动实现的属性(其中相应的字段是"隐藏的"):

private int EachVar {get; set;}