我有class Neighborhood
和public enum State : byte
{
zero = 0,
one = 1,
two = 2
}
public class Neighborhood
{
private State _left, _center, _right;
public Neighborhood(State left, State center, State right)
{
_left = left;
_center = center;
_right = right;
}
public State left { get { return _left; } }
public State center { get { return _center; } }
public State right { get { return _right; } }
}
将它们用作数据。我是C#的新手,所以我不确定这是不是惯用的,或者更简洁(或者说是完全错误的)。
{{1}}
是否有更短或更惯用的方法?
答案 0 :(得分:3)
public enum State : byte
{
zero = 0,
one = 1,
two = 2
}
public class Neighborhood
{
public Neighborhood(State left, State center, State right)
{
this.Left = left;
this.Center = center;
this.Right = right;
}
public State Left { get; private set; }
public State Center { get; private set; }
public State Right { get; private set; }
}
答案 1 :(得分:3)
这可能不是最简单的简明编写方式,但使用readonly
支持字段和private set
自动属性之间存在许多差异:
private set
意味着类实现可以改变属性的值。readonly
支持字段只能从构造函数初始化;类实现不能改变它的价值。readonly
支持字段可以更好地传达 intent ,如果其目的是使不可变。_namingConvention
支持字段会使this
限定符变为冗余。readonly
支持字段的get-only属性本质上是线程安全的;更多信息here。public class Neighborhood
{
public Neighborhood(State left, State center, State right)
{
_left = left;
_center = center;
_right = right;
}
private readonly State _left;
public State Left { get { return _left; } }
private readonly State _center;
public State Center { get { return _center; } }
private readonly State _right;
public State Right { get { return _right; } }
}