Ner*_*ury 53 c# struct cil automatic-properties
如果我使用如下自动属性在C#中定义结构:
public struct Address
{
public Address(string line1, string line2, string city, string state, string zip)
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
Zip = zip;
}
public string Line1 { get; protected set; }
public string Line2 { get; protected set; }
public string City { get; protected set; }
public string State { get; protected set; }
public string Zip { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)
当我尝试构建文件时,我收到编译错误说The 'this' object cannot be used before all of its fields are assigned to.这可以通过更改构造函数来对默认构造函数进行链式调用来解决,如下所示:
public Address(string line1, string line2, string city, string state, string zip): this()
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
Zip = zip;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么这样做,以及发生了什么?我有一个猜测,我试图通过查看IL证明它,但我只是在开玩笑,如果我认为我可以打破IL.但我的猜测是,自动属性通过让编译器在幕后为您的属性生成字段来工作.这些字段无法通过代码访问,所有设置和获取必须通过属性完成.创建结构时,无法显式定义默认构造函数.因此,在幕后,编译器必须生成一个默认构造函数,用于设置开发人员无法看到的字段值.
欢迎任何和所有IL巫师证明或反驳我的理论.
Jon*_*eet 52
注意:从C#6开始,这不是必需的 - 但是您应该使用C#6的只读自动实现的属性...
this()确保在编译器方面明确分配字段 - 它将所有字段设置为其默认值.在开始访问任何属性之前,必须有一个完全构造的结构.
这很烦人,但就是这样.你确定你真的希望这是一个结构吗?为什么在结构上使用受保护的setter(不能从中派生)?