C# Lambda 构建器模式

eth*_*ane 5 c# lambda builder

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

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

但我只想到一种通用的方法来接受 aFunc然后你可以指定要分配的道具:

public Car With<TOut>(Func<Car, TOut> lambda)
{
    lambda.Invoke(this);
    return this;
}
Run Code Online (Sandbox Code Playgroud)

用法:

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");
Run Code Online (Sandbox Code Playgroud)

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

Ous*_* D. 5

您使事情变得过于复杂,相反,您应该利用更简单且更具可读性的对象初始值设定项语法。

var car = new Car { 
     VehicleType = "Sedan", 
     Wheels = 4,
     Colour = "Pink", 
     ... 
};
Run Code Online (Sandbox Code Playgroud)


Seb*_*ann 5

如果你喜欢坚持你原来的方法,我建议以下,它简化了它:

public static T With<T>(this T obj, Action<T> action)
{
     action(obj);
     return obj;
}
Run Code Online (Sandbox Code Playgroud)

此扩展方法允许您以更清晰的方式初始化对象的属性:

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