自动性能和结构 [英] Auto-properties and structs
问题描述
我想了解一下下面的C# - code:
I am wondering about the following C#-code:
struct Structure
{
public Structure(int a, int b)
{
PropertyA = a;
PropertyB = b;
}
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
这是不是一个错误编译在'这个'对象不能使用之前所有字段被分配到。对于类似的类被编译没有任何问题。
It is not compiling with an error "The 'this' object cannot be used before all of its fields are assigned to". For the analogous class it is compiling without any problems.
这可通过重构以下工作:
It can be made working by refactoring to the following:
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#的整点是为了避免以后写code。这是否意味着自动特性是不相关的结构?
But, I though that the whole point of introducing auto-properties to the C# was to avoid writing later code. Does that mean that auto-properties are not relevant for the structs?
推荐答案
在C#6,本的根本消失的;在code。在这个问题编译罚款。
In C# 6, this simply goes away; the code in the question compiles fine.
尽管斯特凡比地址回答这个问题,我的有无的劝你不要用一个可变的结构 - 它的会咬你。可变的结构是邪恶的。
While Stefan has the answer than addresses the question, I have to advise you not to use a mutable struct - it will bite you. Mutable structs are evil.
IMO,正确的解决这里简直是:
IMO, the "correct" fix here is simply:
struct Structure
{
public Structure(int a, int b)
{
propertyA = a;
propertyB = b;
}
private readonly int propertyA, propertyB;
public int PropertyA { get { return propertyA; } }
public int PropertyB { get { return propertyB; } }
}
这篇关于自动性能和结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!