下面是一个简单的代码,我声明了一个变量startingMileage
,并在方法中为其赋值。
但是我收到以下错误:
字段初始值设定项无法引用非静态字段、方法或属性
public partial class Form1 : Form
{
int startingMileage;
//I get the error if I directly assign value like this:
//int startingMileage = (int)numericUpDown1.Value;
double reimburseRate = 0.39; //here I can directly assign value to variable
private void button1_Click(object sender, EventArgs e)
{
startingMileage = (int)numericUpDown1.Value; // assign the value inside method is ok
}
}
我的问题是:为什么我不能直接将该值赋给它?
正如错误消息所示,numericUpDown1.Value 是 Form 类的非静态字段 (numericUpDown1) 的属性,在执行赋值时它没有值,但 0.39 是一个常量,可以将其分配给该字段任何时候。
此外,如果编译器允许您编译该代码,您将收到运行时异常,因为 UI 控件(例如 numbericUpDown1)在 Form 构造函数(InitializeComponent 方法)中实例化,该构造函数在 Form 类的字段初始化之后执行。
如果合并设计器代码,它将如下所示:
public partial class Form1 : Form {
NumbericUpDown numericUpDown1;
int startingMileage = (int)numericUpDown1.Value;
double reimburseRate = 0.39;
..
..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)