gpt4 book ai didi

C# Lambda 构建器模式

转载 作者:太空狗 更新时间:2023-10-30 00:48:06 26 4
gpt4 key购买 nike

我有一个类,它有 11 个属性(大部分是继承的)。我不太喜欢传入 11 个参数。我知道我可以创建一个 ModelBuilder 类并执行以下操作:

new ModelBuilder().WithProp1(prop1).WithProp2(prop2).Build();

但我只考虑了一种通用的方法,足以接受 Func,然后您可以指定要分配的 prop:

public Car With<TOut>(Func<Car, TOut> lambda)
{
lambda.Invoke(this);
return this;
}

用法:

var car = new Car()
.With(x => x.VehicleType = "Sedan")
.With(x => x.Wheels = 4)
.With(x => x.Colour = "Pink")
.With(x => x.Model = "fancyModelName")
.With(x => x.Year = "2007")
.With(x => x.Engine = "Large")
.With(x => x.WeightKg = 2105)
.With(x => x.InvoiceNumber = "1234564")
.With(x => x.ServicePlanActive = true)
.With(x => x.PassedQA = false)
.With(x => x.Vin = "blabla");

这似乎有效。我的问题:在实现方面我是否遗漏了什么(除了明显的 - 将此方法拖到接口(interface)或帮助类)?是否有任何我忽略的实现可能会出现的问题?

最佳答案

如果您想坚持原来的方法,我建议采用以下方法来简化它:

public static T With<T>(this T obj, Action<T> action)
{
action(obj);
return obj;
}

这个扩展方法可以让您以更简洁的方式初始化对象的属性:

var car = new Car().With(c =>
{
c.VehicleType = "Sedan";
c.Model = "fancyModelName";
//and so on
});

关于C# Lambda 构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816190/

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