C#中不可变数据类的最简洁形式是什么?

时间:2015-07-09 03:59:44

标签: c# oop properties immutability

我有class Neighborhoodpublic 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}}

是否有更短或更惯用的方法?

2 个答案:

答案 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; } }
}