在C#中创建不可变类的最简洁方法是什么?

Cha*_*ion 8 c# tuples immutability

我发现自己必须创建许多不可变的类,我想找到一种方法来做到这一点,没有多余的信息.我不能使用匿名类型,因为我需要从方法返回这些类.我想要intellisense支持,所以我不想使用Dictionaries,动态或类似的东西.我还想要有名的属性,它排除了元组<>.到目前为止,我尝试过一些模式:

// inherit Tuple<>. This has the added benefit of giving you Equals() and GetHashCode()
public class MyImmutable : Tuple<int, string, bool> {
   public MyImmutable(int field1, string field2, bool field3) : base(field1, field2, field3) { }

   public int Field1 { get { return this.Item1; } }
   public string Field2 { get { return this.Item2; } }
   public bool Field3 { get { return this.Item3; } }
}

///////////////////////////////////////////////////////////////////////////////////

// using a custom SetOnce<T> struct that throws an error if set twice or if read before being set
// the nice thing about this approach is that you can skip writing a constructor and 
// use object initializer syntax.
public class MyImmutable {
    private SetOnce<int> _field1;
    private SetOnce<string> _field2;
    private SetOnce<bool> _field3;


   public int Field1 { get { return this._field1.Value; } set { this._field1.Value = value; }
   public string Field2 { get { return this._field2.Value; } set { this._field2.Value = value; }
   public bool Field3 { get { return this._field3.Value; } set { this._field3.Value = value; }
}

///////////////////////////////////////////////////////////////////////////////////

// EDIT: another idea I thought of: create an Immutable<T> type which allows you to
// easily expose types with simple get/set properties as immutable
public class Immutable<T> {
    private readonly Dictionary<PropertyInfo, object> _values;       

    public Immutable(T obj) {
        // if we are worried about the performance of this reflection, we could always statically cache
        // the getters as compiled delegates
        this._values = typeof(T).GetProperties()
            .Where(pi => pi.CanRead)
            // Utils.MemberComparer is a static IEqualityComparer that correctly compares
            // members so that ReflectedType is ignored
            .ToDictionary(pi => pi, pi => pi.GetValue(obj, null), Utils.MemberComparer);
    }

    public TProperty Get<TProperty>(Expression<Func<T, TProperty>> propertyAccessor) {
        var prop = (PropertyInfo)((MemberExpression)propertyAccessor.Body).Member;
        return (TProperty)this._values[prop];
    }
}

// usage
public class Mutable { int A { get; set; } }

// we could easily write a ToImmutable extension that would give us type inference
var immutable = new Immutable<Mutable>(new Mutable { A = 5 });
var a = immutable.Get(m => m.A);

// obviously, this is less performant than the other suggestions and somewhat clumsier to use.
// However, it does make declaring the immutable type quite concise, and has the advantage that we can make
// any mutable type immutable

///////////////////////////////////////////////////////////////////////////////////

// EDIT: Phil Patterson and others mentioned the following pattern
// this seems to be roughly the same # characters as with Tuple<>, but results in many
// more lines and doesn't give you free Equals() and GetHashCode()
public class MyImmutable 
{
   public MyImmutable(int field1, string field2, bool field3)
   {
        Field1 = field1;
        Field2 = field2;
        Field3 = field3;
   }

   public int Field1 { get; private set; }
   public string Field2 { get; private set; }
   public bool Field3 { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

这些都比创建只读字段,通过构造函数设置它们并通过属性公开它们的"标准"模式稍微冗长一些.但是,这两种方法仍然有很多冗余的样板.

有任何想法吗?

Ale*_*kov 1

看看public {get;private set;}属性是否适合您的情况 - 比单独的字段声明更紧凑一点,语义完全相同。

更新:正如 ChaseMedallion 在问题中评论和内联的那样,该方法不提供自动生成的方法GetHashCode,而Equals方法与方法不同Tuple

class MyImmutable 
{
    public int MyProperty {get; private set;}

    public MyImmutable(int myProperty)
    {
       MyProperty = v;
    }
}
Run Code Online (Sandbox Code Playgroud)

我喜欢Tuple这种方法,因为它提供了可以在有趣的上下文中安全使用的对象,并提供了漂亮的名称。如果我需要创建许多此类类型,我会考虑重新实现Tuple类:

  • 在构造时预先计算GetHashCode 并存储为对象的一部分,以避免对集合/字符串进行无限制的检查。可能是可选的,允许选择通常用作 中的键的情况Dictionary
  • 隐藏通用名称(即或只是使用EditorBrowsableAttributeprotected隐藏智能),因此 2 组名称不会混淆。
  • 考虑在调试构建/FxCop 规则中强制字段类型不可变...

旁注:查看 Eric Lippert 的不可变类型系列