如果我在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; }
}
当我尝试构建文件时,我遇到了编译错误,提示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;
}
我的问题是,为什么这个方法有效,发生了什么?我有一个猜想,并试图通过查看IL证明它,但如果我认为我可以分解IL,那只是在自欺欺人。但我的猜测是,自动属性通过使编译器在幕后生成属性的字段来工作。这些字段不能通过代码访问,所有的设置和获取都必须通过属性完成。创建结构时,不能显式定义默认构造函数。因此,在幕后,编译器必须生成一个默认构造函数,设置开发者看不到的字段的值。
任何IL专家都可以验证或反驳我的理论。