如果我使用这样的自动属性在 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 向导来证明或反驳我的理论。