C# Why can I create an array of labels inside a function but not anywhere else?

你离开我真会死。 提交于 2019-12-24 12:08:07

问题


When I put the code:

label[] label_array = {label1, label2};

Inside of a function, it works just fine. Whenever I put it anywhere else, I get the error "A field initializer cannot reference the non-static field, method, or property, file.form1.label1"

Is there a different way that I can do it that will allow me to make the label array global?


回答1:


You can't write that at the class level, because when the variable initialization runs those labels don't exist yet. If you want the variable at the class level, just declare it there:

label[] label_array;

Then initialize it in the constructor (or some other function like an Init function):

private void Init()
{
    label_array = new label[2] {label1, label2};
}



回答2:


I guess you mean the class level by anyhwere else, if you want to make it a class level variable, you could declare your array in class level then initialize it in a method,for example in a constructor.

C# doesn't have global variables,class level is the widest range that a variable can have.



来源:https://stackoverflow.com/questions/24375208/c-sharp-why-can-i-create-an-array-of-labels-inside-a-function-but-not-anywhere-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!