问题
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