Why am I getting an error indicating that my variable doesn't exist, when I've already defined it?

♀尐吖头ヾ 提交于 2021-02-17 06:10:13

问题


I get an error indicating that MyRandomArray doesn't exist in the current context. How do you access variables across classes in a C# WinForms application?

public void Quiz_Load(object sender, EventArgs e)
{
    string[] MyRandomArray = getWordList();
}

private void timer1_Tick(object sender, EventArgs e)
{
    somefunction(MyRandomArray);/// MyRandomArray doesn't exist in the current context.
}

回答1:


You've defined the array, but only in the scope of the Quiz_Load method, so the scope of timer1_Tick has no knowledge of it. If you declare it as an instance member of the class, it will be accessible from any instance method:

private string[] MyRandomArray;

public void Quiz_Load(object sender, EventArgs e)
{
    this.MyRandomArray = getWordList();
}

private void timer1_Tick(object sender, EventArgs e)
{
   somefunction(this.MyRandomArray); // No problem
}

Further Reading

  • Scope (C#)



回答2:


MyRandomArray is local to the Quiz_Load method; therefore you can't see it in the timer1_Tick method. You'll have to use a field to store the array if you need it visible across instance methods:

private string[] MyRandomArray;

public void Quiz_Load(object sender, EventArgs e) {
    this.MyRandomArray = getWordList();
}

private void timer1_Tick(object sender, EventArgs e) {
    somefunction(this.MyRandomArray);
}

Alternatively, since you have a timer ticking, when you set up the timer callback you could have, as part of the callback state you could pass along MyRandomArray.



来源:https://stackoverflow.com/questions/17712671/why-am-i-getting-an-error-indicating-that-my-variable-doesnt-exist-when-ive-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!