C# 在当前上下文中不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2123630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# does not exist in the current context
提问by Qrew
public void DoStuff()
{
List<Label> RpmList = new List<Label>();
RpmList.Add(label0x0);
RpmList.Add(label0x1);
RpmList.Add(label0x2);
RpmList[0].BackColor = System.Drawing.Color.Yellow;
}
public void Form1_Load(object sender, EventArgs e)
{
DoStuff();
RpmList[1].BackColor = System.Drawing.Color.Yellow; // <---THIS ONE
}
How can I access the listinside DoStuff() method from all my other classes?
Inside DoStuff() method I access Form1
labels.
如何从所有其他类访问DoStuff() 方法中的列表?
在 DoStuff() 方法中,我访问Form1
标签。
回答by Paul Creasey
You should read about variable scope
您应该阅读有关变量范围的信息
回答by Cipi
First of all method names can be other then that.
首先,方法名称可以是其他名称。
Second, declare RpmList
like this:
其次,声明RpmList
如下:
class ClassName
{
List<Label> RpmList = new List<Label>();
public void DoStuff()
{
RpmList.Add(label0x0);
RpmList.Add(label0x1);
RpmList.Add(label0x2);
RpmList[0].BackColor = System.Drawing.Color.Yellow;
}
}
回答by tvanfosson
Return the list from the method and assign it to a local variable, then use the local variable.
从方法返回列表并将其分配给局部变量,然后使用局部变量。
private List<Label> DoSomething()
{
...
return RpmList;
}
...
var list = DoSomething();
list[0].BackColor = ...
回答by romiem
Your RpmList variable is private to the DoStuff method. You need to move it out the method which makes it a global variable and therefore has scope to the entire class. I would recommend reading up about Object Oriented Programming because you are offending a very basic law to the whole methodology (encapsulation and variable scope). Anyway, to resolve your problem:
您的 RpmList 变量是 DoStuff 方法的私有变量。您需要将它移出方法,使其成为全局变量,因此具有整个类的范围。我建议阅读有关面向对象的编程,因为您违反了整个方法论(封装和变量范围)的一个非常基本的法律。无论如何,要解决您的问题:
List<Label> RpmList = new List<Label>();
public void DoStuff()
{
RpmList.Add(label0x0);
RpmList.Add(label0x1);
RpmList.Add(label0x2);
RpmList[0].BackColor = System.Drawing.Color.Yellow;
}
public void Form1_Load(object sender, EventArgs e)
{
DoStuff();
RpmList[1].BackColor = System.Drawing.Color.Yellow; // <---THIS ONE
}