C#Lambda Builder模式

时间:2018-04-13 11:42:40

标签: c# lambda builder

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

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

但我只想到一种通用的方法足以接受Func,然后您可以指定要分配的道具:

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");

这似乎有效。我的问题:在实现方面我有什么遗漏吗(除非显而易见 - 将此方法拖到接口或辅助类中)?是否有任何可能与我忽略的实现有关的陷阱?

2 个答案:

答案 0 :(得分:3)

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

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
});

答案 1 :(得分:2)

你过度复杂化了,相反,你应该利用更简单,更易读的对象初始化语法。

var car = new Car { 
     VehicleType = "Sedan", 
     Wheels = 4,
     Colour = "Pink", 
     ... 
};