C# Why can I create an array of labels inside a fu

2019-08-09 04:58发布

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?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-09 05:30

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};
}
查看更多
何必那么认真
3楼-- · 2019-08-09 05:33

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.

查看更多
登录 后发表回答