我想知道以下 C# 代码:
struct Structure
{
public Structure(int a, int b)
{
PropertyA = a;
PropertyB = b;
}
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
它没有编译错误“在分配所有字段之前不能使用'this'对象”。对于类似的类,它的编译没有任何问题。
可以通过重构以下内容来使其工作:
struct Structure
{
private int _propertyA;
private int _propertyB;
public Structure(int a, int b)
{
_propertyA = a;
_propertyB = b;
}
public int PropertyA
{
get { return _propertyA; }
set { _propertyA = value; }
}
public int PropertyB
{
get { return _propertyB; }
set { _propertyB = value; }
}
}
但是,我认为将自动属性引入 C# 的全部目的是避免编写以后的代码。这是否意味着自动属性与结构无关?