如何使用C#返回类的新实例的setter? (使对象不可变)

时间:2016-04-22 08:06:05

标签: c# immutability

我有一个具有多个具有getter和setter的属性的类。我想让这个类的对象不可变。我想给setter一个返回类型而不是像 System.Collections.Immutable 类中的函数那样的void。现在我这样做了:

MyImmutableClass
{
    public int MyAttribute { get; }
    public MyImmutableClass SetMyAttribute(int attribute)
    {
        return new MyImmutableClass(attribute, ...);
    }

    ...

    public MyImmutableClass(int attribute, ...)
    {
        MyAttribute = attribute;
        ...
    }
}

这是应该如何完成还是有更好/更好的方式?我可以修改一个普通的setter吗?

1 个答案:

答案 0 :(得分:2)

您应该使用静态工厂方法并使用私有构造函数,不会为此创建属性(因为创建对象可能需要做很多工作 - >使用方法)。您可以在create方法中执行所有操作,通过使用与您一样的只读属性,可以为您提供无法修改的对象:

public class MyImmutableClass
{
   public int MyAttribute { get; }

   private MyImmutableClass(int attribute, ...)
   {
       MyAttribute = attribute;
       ...
   }

   public static MyImmutableClass Create(int attribute)
   {
       return new MyImmutableClass(attribute, ...);
   }
}

然后使用它:

var myClass = MyImmutableClass.Create(2);