编译器显示未分配的结构对象字段和 属性 的不同错误
compiler showing different errors for unassigned struct object field and property
在下面 line:1 的代码中,编译器显示错误 :"Use of possibly unassigned field 'IntField' " 但第 2 行的错误是 "Use of possibly unassigned local variable 'structObj' " 。为什么会出现不同的错误?
class Program
{
static void Main(string[] args)
{
StructA structObj;
Console.WriteLine(structObj.IntField); //Line :1
Console.WriteLine(structObj.IntProperty); //Line :2
Console.ReadKey();
}
}
struct StructA
{
public int IntField;
public int IntProperty { get; set; }
}
因为StructA
是一个结构体而IntField
是一个字段。
在使用之前先尝试 StructA structObj = new StructA()
。
我认为错误之间差异的原因是 属性 被转换为方法。并且无法在未初始化的对象上调用方法。
这里需要为结构调用new(),因为如果不使用New运算符,字段将保持未赋值状态,在所有字段初始化之前无法使用对象。
所以 属性 的值初始化必须是
StructA structObj = new StructA();
您可以尝试不对结构中的变量使用 new,但需要初始化,因此只需像
一样赋值
structObj.IntField= 1;
但是对于 属性 你需要 new()。
在下面 line:1 的代码中,编译器显示错误 :"Use of possibly unassigned field 'IntField' " 但第 2 行的错误是 "Use of possibly unassigned local variable 'structObj' " 。为什么会出现不同的错误?
class Program
{
static void Main(string[] args)
{
StructA structObj;
Console.WriteLine(structObj.IntField); //Line :1
Console.WriteLine(structObj.IntProperty); //Line :2
Console.ReadKey();
}
}
struct StructA
{
public int IntField;
public int IntProperty { get; set; }
}
因为StructA
是一个结构体而IntField
是一个字段。
在使用之前先尝试 StructA structObj = new StructA()
。
我认为错误之间差异的原因是 属性 被转换为方法。并且无法在未初始化的对象上调用方法。
这里需要为结构调用new(),因为如果不使用New运算符,字段将保持未赋值状态,在所有字段初始化之前无法使用对象。
所以 属性 的值初始化必须是
StructA structObj = new StructA();
您可以尝试不对结构中的变量使用 new,但需要初始化,因此只需像
一样赋值structObj.IntField= 1;
但是对于 属性 你需要 new()。