字段初始化程序无法引用非静态字段C# [英] Field initializer cannot reference the nonstatic field C#
问题描述
int temp = MCUData[temp_i];
int temp2 = MCUData[temp_i + 1];
int result;
int temp1;
temp1 = MCUData[temp_i] << 8;
result = temp1 | temp2;
crc_register = result;
int temp_int;
if (result == crc_register)
{
j = 0;
for (i = 3; i<no_of_bytes + 3;)
{
temp_buf[j++] = MCUData[i++];
}
row = 0;
col = 1;
k = 0;
//
dataGridView1.Rows[row++].Cells[col].Value = temp_buf[k++];
}}
我的尝试:
字段初始化程序无法引用非静态字段c#
What I have tried:
field initializer cannot reference the nonstatic field c#
推荐答案
该代码不完整 - 它不包含导致错误的行。 br $> b $ b
但是......信息非常明确:
That code is incomplete - it doesn't contain the line that causes the error.
But ... the message is pretty clear:
field initializer cannot reference the nonstatic field
它的含义是你不能使用同一个类中另一个字段的值来初始化类级别字段(或变量)的值。即这是非法的:
What it is saying is that you can't initialize the value of a class level field (or variable) using the value of another field in the same class. I.e. this is illegal:
public class MyClass
{
int x = 666;
int y = x;
}
如果你考虑一下,这是有意义的:如果编译器移动了初始化怎么办?如果它确实 - 它可以 - 那么在x被赋予值666之前y将被设置为x的值。
没有修复对于这个作为一般规则,最有可能的是,如果你真的需要这样做,那么两个初始化都属于类构造函数:
If you think about it, it makes sense: what if the compiler moved the initialisations around? If it did - and it can - then y would be set to the value of x before x was given the value 666.
There isn't a "fix" for this as a general rule, it's most likely that if you genuinely need to do this then both initializations belong in the class constructor:
public class MyClass
{
int x;
int y;
public MyClass()
{
x = 666;
y = x;
}
}
这篇关于字段初始化程序无法引用非静态字段C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!