如何分配Func<>使用条件三元运算符在lambda之间有条件地? [英] How can I assign a Func<> conditionally between lambdas using the conditional ternary operator?

查看:72
本文介绍了如何分配Func<>使用条件三元运算符在lambda之间有条件地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,使用条件运算符时,语法如下:

Generally, when using the conditional operator, here's the syntax:

int x = 6;
int y = x == 6 ? 5 : 9;

没什么好想的,很简单.

Nothing fancy, pretty straight forward.

现在,让我们在将Lambda分配给Func类型时尝试使用它.让我解释一下:

Now, let's try to use this when assigning a Lambda to a Func type. Let me explain:

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

这是相同的语法,应该有效吗?正确的?由于某种原因,那不是.编译器给出了以下信息:

That's the same syntax, and should work? Right? For some reason that doesn't. The compiler gives this nice cryptic message:

错误1无法确定条件表达式的类型,因为'lambda表达式'和'lambda表达式'之间没有隐式转换

Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

然后我继续并更改了语法,使它 did 工作:

I then went ahead and changed the syntax and this way it did work:

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

我很好奇为什么它不能一开始起作用?

I'm just curious as to why it doesn't work the first way?

(附带说明:我最终不需要此代码,因为我发现将int值与null进行比较时,只需使用object.Equals).

(Side note: I ended up not needing this code, as I found out that when comparing an int value against null, you just use object.Equals)

推荐答案

您可以将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.

这篇关于如何分配Func&lt;&gt;使用条件三元运算符在lambda之间有条件地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆