如何使 return 的设置器成为 C# 中 class 的新实例? (用于使对象不可变)
How to make setters that return a new instance of the class in C#? (for making objects immutable)
我有一个 class,其中有几个属性具有 getter 和 setter。我想让这个 class 的对象不可变。我想给 setters 一个 return 类型而不是 void 就像 System.Collections.Immutable classes 中的函数一样。现在我是这样做的:
MyImmutableClass
{
public int MyAttribute { get; }
public MyImmutableClass SetMyAttribute(int attribute)
{
return new MyImmutableClass(attribute, ...);
}
...
public MyImmutableClass(int attribute, ...)
{
MyAttribute = attribute;
...
}
}
是应该这样做还是有 better/nicer 方法?例如,我可以修改一个普通的 setter 吗?
您应该使用静态工厂方法并使用私有构造函数,不为此创建属性(因为创建对象可能需要大量工作 -> 使用一个方法)。您在 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);
我有一个 class,其中有几个属性具有 getter 和 setter。我想让这个 class 的对象不可变。我想给 setters 一个 return 类型而不是 void 就像 System.Collections.Immutable classes 中的函数一样。现在我是这样做的:
MyImmutableClass
{
public int MyAttribute { get; }
public MyImmutableClass SetMyAttribute(int attribute)
{
return new MyImmutableClass(attribute, ...);
}
...
public MyImmutableClass(int attribute, ...)
{
MyAttribute = attribute;
...
}
}
是应该这样做还是有 better/nicer 方法?例如,我可以修改一个普通的 setter 吗?
您应该使用静态工厂方法并使用私有构造函数,不为此创建属性(因为创建对象可能需要大量工作 -> 使用一个方法)。您在 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);