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

What is the most concise form of an immutable data class in C#?

我有一个 enum State 和一个 class Neighborhood 将它们用作数据。我是 C# 的新手,所以我不确定这是惯用的还是可以更简洁(或者完全错误)。

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

是否有更短或更惯用的方法来做到这一点?

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

这可能不是最简明的写法,但是使用 readonly 支持字段和 private set auto 之间有很多区别-属性:

  • private set 意味着 class 实现可以改变 属性.
  • 的值
  • readonly 支持字段只能从构造函数中初始化; class 实现不能改变它的值。
  • readonly 支持字段可以更好地传达 意图 ,如果该意图是使某些东西 immutable.
  • 带有 _namingConvention 的支持字段使 this 限定符变得多余。
  • get-only 属性 with a readonly backing field 本质上是线程安全的;更多信息 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; } }
}