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

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

问题描述

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

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'

然后我继续更改语法,这样它确实起作用了:

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;使用条件三元运算符有条件地在 lambdas 之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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