我知道Func<>
s不能通过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作业?
答案 0 :(得分:10)
var filter = (someBooleanExpressionHere)
? new Func<Something, bool>(x => x.SomeProp < 5)
: x => x.SomeProp >= 5;
答案 1 :(得分:3)
您应该将它们包装在new Func
中,否则它无法将一个lamdba转换为另一个:
Func<Something, bool> filter = (someBooleanExpressionHere)
? new Func<Something, bool>(x => x.SomeProp < 5)
: x => x.SomeProp >= 5
;
如果您删除new Func...
,则会获得:
无法确定条件表达式的类型,因为&#39; lambda表达式&#39;之间没有隐式转换。和&#39; lambda表达&#39;
答案 2 :(得分:1)
您可以明确提及类型作为编译器的提示
var filter = (condition)
? (Func<Something, bool>)(x => x.SomeProp < 5)
: x => x.SomeProp >= 5;
答案 3 :(得分:1)
如果合适,您可以将这些选择器分配给静态字段。
private static readonly Func<Something, bool> _someFilter = x => x.SomeProp < 5;
private static readonly Func<Something, bool> _someOtherFilter = x => x.SomeProp >= 5;
您可以稍后再使用它们。
var filter = (someBooleanExpressionHere) ? _someFilter : _someOtherFilter;