我对保持不变性的最简洁方法感到很困惑。
这是迄今为止我得到的最简单和最愚蠢的方法,但我仍然想知道是否有更简单的方法来实现这一点
class MyClass
{
public int Property1 { get; }
public string Property2 { get; }
public MyClass CopyWith(int? property1 = default, string property2 = default)
{
return new MyClass
{
Property1 = property1 ?? Property1,
Property2 = property2 ?? Property2
};
}
}
class Program
{
static void Main()
{
var myObj = new MyClass { Property1 = 123, Property2 = "123" };
var myModifiedObj = myObj.CopyWith(property2: "456");
}
}
使用泛型的扩展方法会涉及很多反射(reflection),但我仍然相信我想得太多了,也许我缺少一个更简单的解决方案......
最佳答案
要拥有不可变类您首先需要确保无法从外部访问其属性。所以我将其更改为:
class MyClass
{
public int Property1 { get; }
public string Property2 { get; }
public MyClass(int prp1, string prp2)
{
Property1 = prp1;
Property2 = prp2;
}
public MyClass With(int? property1 = default, string property2 = default) =>
new MyClass(property1 ?? Property1, property2 ?? Property2);
}
这已经是一个很好的起点。正如您所说,使用泛型可能意味着过度设计您要解决的问题的代码。
有些人更喜欢对您要更改的每个属性使用一种方法,如果他们想更改多个属性,则将调用链接起来。这可能看起来有点冗长,但通常会产生更清晰的类。
看起来像这样:
class MyClass
{
// until here it is the same as before
public MyClass WithPrp1(int prp1) => new MyClass(prp1,Property2);
public MyClass WithPrp2(string prp2) => new MyClass(Property1,prp2);
}
class Program
{
static void Main()
{
var myObj = new MyClass(123, "123");
var myModifiedObj = myObj.WithPrp1(456).WithPrp2("789");
}
}
关于c# - 在不破坏不变性的情况下更改属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60473734/