0

我收到一个错误,表明MyRandomArray当前上下文中不存在该错误。如何在 C# WinForms 应用程序中跨类访问变量?

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

2 回答 2

8

您已经定义了数组,但Quiz_Load方法的范围内,因此范围timer1_Tick不知道它。如果将其声明为类的实例成员,则可以从任何实例方法访问它:

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
}

延伸阅读

于 2013-07-18T00:46:54.660 回答
4

MyRandomArray是方法本地Quiz_Load;因此您在方法中看不到它timer1_Tick。如果需要跨实例方法可见,则必须使用字段来存储数组:

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

或者,由于您有一个计时器滴答作响,因此当您设置计时器回调时,您可以将其作为回调状态的一部分传递MyRandomArray

于 2013-07-18T00:46:32.380 回答