C#为什么我可以在函数内部创建标签的数组而不是其他地方? [英] C# Why can I create an array of labels inside a function but not anywhere else?

查看:121
本文介绍了C#为什么我可以在函数内部创建标签的数组而不是其他地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我把code:

 标签[] = label_array {LABEL1,LABEL2};

里面的函数,它工作得很好。每当我把它放在其他地方,我得到的错误一个字段初始不能引用非静态字段,方法或属性,file.form1.label1

是否有不同的方式,我可以做到这一点,让我做标签阵列全球性的?


解决方案

您可以不写,在一流水平,因为当变量初始化运行的还不存在这些标签的。如果你想在类级别的变量,只是声明它有:

 标签[] label_array;

然后在构造函数(或其他一些功能像初始化功能)初始化

 私人无效的init()
{
    label_array =新的标签[2] {LABEL1,LABEL2};
}

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?

解决方案

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};
}

这篇关于C#为什么我可以在函数内部创建标签的数组而不是其他地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆