本文介绍了当我已经定义了变量时,为什么会收到错误消息,指出我的变量不存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我收到一个错误,指出 MyRandomArray
在当前上下文中不存在.如何在 C# WinForms 应用程序中跨类访问变量?
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.
}
推荐答案
您已经定义了数组,但是仅在 Quiz_Load
方法的范围内,因此timer1_Tick
的范围不知道它.如果将其声明为类的实例成员,则可以从任何实例方法访问它:
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
}
进一步阅读
作用域 (C#)这篇关于当我已经定义了变量时,为什么会收到错误消息,指出我的变量不存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论