我想了解以下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#的整个目的是避免编写后续代码。这是否意味着自动属性对结构体不相关?