C# does not exist in the current context
public void DoStuff()
{
List<Label> RpmList = new List<Label>();
RpmList.Add(label0x0);
RpmList.Add(label0x1);
RpmList.Add(label0x2);
RpmList[0].BackColor =开发者_StackOverflow中文版 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 list inside DoStuff() method from all my other classes?
Inside DoStuff() method I accessForm1
labels.You should read about variable scope
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 = ...
First of all method names can be other then that.
Second, declare RpmList
like this:
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;
}
}
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:
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
}
精彩评论