重构为消除重复在Lambda表达式 [英] Refactor To Eliminate Repetition In Lambda Expression
本文介绍了重构为消除重复在Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这两种方法表现出重复:
These two methods exhibit repetition:
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => new FooEditDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC,
PropertyD = f.PropertyD,
PropertyE = f.PropertyE
};
}
public static Expression<Func<Foo, FooListDto>> ListDtoSelector()
{
return f => new FooDto
{
PropertyA = f.PropertyA,
PropertyB = f.PropertyB,
PropertyC = f.PropertyC
};
}
如何重构来消除这种重复?
How can I refactor to eliminate this repetition?
更新:哎呀,我忘了提及的重要一点。 FooEditDto是FooDto的子类。
UPDATE: Oops, I neglected to mention an important point. FooEditDto is a subclass of FooDto.
推荐答案
如果 FooEditDto
是一个sublass的 FooDto
键,您不需要MemberInitExpressions,使用构造函数:
If FooEditDto
is a sublass of FooDto
and you don't need the MemberInitExpressions, use a constructor:
class FooDto
{ public FooDto(Bar a, Bar b, Bar c)
{ PropertyA = a;
PropertyB = b;
PropertyC = c;
}
public Bar PropertyA {get;set;}
public Bar PropertyB {get;set;}
public Bar PropertyC {get;set;}
}
class FooEditDto : FooDto
{ public FooEditDto(Bar a, Bar b, Bar c) : base(a,b,c)
public Bar PropertyD {get;set;}
public Bar PropertyE {get;set;}
}
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => new FooEditDto(f.PropertyA,f.PropertyB,f.PropertyC)
{
PropertyD = f.PropertyD,
PropertyE = f.PropertyE
};
}
这篇关于重构为消除重复在Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文