gpt4 book ai didi

c# - 不可变设计 : Dealing with Constructor Insanity

转载 作者:IT王子 更新时间:2023-10-29 04:53:44 25 4
gpt4 key购买 nike

出于各种原因,我想开始在设计中使用更多不可变类型。目前,我正在处理一个现有类如下的项目:

public class IssueRecord
{
// The real class has more readable names :)
public string Foo { get; set; }
public string Bar { get; set; }
public int Baz { get; set; }
public string Prop { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public string Prop4 { get; set; }
public string Prop5 { get; set; }
public string Prop6 { get; set; }
public string Prop7 { get; set; }
public string Prop8 { get; set; }
public string Prop9 { get; set; }
public string PropA { get; set; }
}

这个类代表了一些确实有这么多属性的磁盘格式,所以在这一点上将它重构为更小的位几乎是不可能的。

这是否意味着此类的构造函数在不可变设计中真的需要有 13 个参数?如果不是,如果我要使这个设计不可变,我可以采取什么步骤来减少构造函数中接受的参数数量?

最佳答案

要减少参数的数量,您可以将它们分组到合理的集合中,但要拥有真正不可变的对象,您必须在构造函数/工厂方法中对其进行初始化。

有些变体是创建“构建器”类,您可以使用流畅的界面进行配置,而不是请求最终对象。如果您实际上计划在代码的不同位置创建许多此类对象,那么这将是有意义的,否则在一个地方使用多个参数可能是可以接受的权衡。

var immutable = new MyImmutableObjectBuilder()
.SetProp1(1)
.SetProp2(2)
.Build();

关于c# - 不可变设计 : Dealing with Constructor Insanity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12291621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com