且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何分配一个 Func<>使用条件三元运算符有条件地在 lambdas 之间?

更新时间:2022-12-17 14:33:42

您可以将 lambda 表达式转换为特定的目标委托类型,但是为了确定条件表达式的类型,编译器需要知道每个第二和第三操作数.虽然它们都只是lambda 表达式",但没有从一个到另一个的转换,所以编译器不能做任何有用的事情.

You can convert a lambda expression to a particular target delegate type, but in order to determine the type of the conditional expression, the compiler needs to know the type of each of the second and third operands. While they're both just "lambda expression" there's no conversion from one to the other, so the compiler can't do anything useful.

我不建议使用赋值,但是 - 演员表更明显:

I wouldn't suggest using an assignment, however - a cast is more obvious:

Func<Order, bool> predicate = id == null 
    ? (Func<Order, bool>) (p => p.EmployeeID == null)
    : p => p.EmployeeID == id;

请注意,您只需为一个操作数提供它,以便编译器可以执行从另一个 lambda 表达式的转换.

Note that you only need to provide it for one operand, so the compiler can perform the conversion from the other lambda expression.