This question already has answers here:
How can I assign a Func<> conditionally between lambdas using the conditional ternary operator?

(3个答案)


4年前关闭。




我知道Func<>不能直接通过var关键字隐式键入,尽管我希望我可以对谓词进行以下赋值:
Func<Something, bool> filter = (someBooleanExpressionHere)
   ? x => x.SomeProp < 5
   : x => x.SomeProp >= 5;

但是,我收到错误cannot resolve the symbol, 'SomeProp'
此刻,我求助于较为繁琐的if branch分配,这似乎并不优雅。
Func<Something, bool> filter;
if (someBooleanExpressionHere)
{
    filter = x => x.SomeProp < 5;
}
else
{
    filter = x => x.SomeProp >= 5;
}

我错过了什么吗?还是需要坚持if-branch作业?

最佳答案

var filter = (someBooleanExpressionHere)
   ? new Func<Something, bool>(x => x.SomeProp < 5)
   : x => x.SomeProp >= 5;

10-03 00:03