我在想我应该能够使用某种Expression作为下面最终方法的参数,但我还是无法解决这个问题。
我该怎么做?
干杯,
Berryl
class Detail{
string DisplayName{get;set;}
string SpanishName{get;set;}
string FrenchName{get;set;}
}
class Master{
IEnumerable<Detail> AllDetail{get;set;}
bool DoSpanish(get;set;)
bool DoFrench(get;set;)
_flipDisplayName(){
DoSpanish
? _flipDisplayName(x=>x.SpanishName)
: _flipDisplayName(x=>x.FrenchName);
}
// *****************************************************
_flipDisplayName(????){ <==== Expression??
foreach(Detail detail in AllDetail) detail.DisplayName = ???;
}
}
答案 0 :(得分:4)
尝试类似
的内容_flipDisplayName(Func<Detail, string> name){
foreach(Detail detail in AllDetail)
detail.DisplayName = name(detail);
}
由于您不需要分析传入的表达式,Func<,>
就足够了。
您还可以使用Expression<Func<,>>
来解析所提供的表达式,以确定它是否引用了英语或西班牙语属性,但在这种情况下这不是必需的。
答案 1 :(得分:1)
如果我理解你的目标,你可以这样做:
private void _flipDisplayName(Func<Detail, string> displayFunc)
{
foreach(Detail detail in AllDetail)
detail.displayFunc(detail);
}
另一个重载可能是:
private void _flipDisplayName()
{
this.DoSpanish ? _flipDisplayName(x => x.SpanishName)
: _flipDisplayName(x => x.FrenchName);
}
答案 2 :(得分:0)
结帐Get value from ASP.NET MVC Lambda Expression。这是在MVC的背景下,但答案适用于任何地方。