lambda表达式和条件运算符,奇怪的问题。 [英] Lambdas and the conditional operator, weird issue.

查看:446
本文介绍了lambda表达式和条件运算符,奇怪的问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般情况下,使用条件运算符的时候,这里的语法:​​

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

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

没什么特别,pretty直线前进。

Nothing fancy, pretty straight forward.

现在,让我们尝试一个Func键类型分配的lambda时使用此。让我来解释一下:

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类型条件前pression不能确定,因为有'拉姆达前pression'和'拉姆达前pression'之间的隐式转换

然后我继续和改变的语法和这种方式,它的没有的工作:

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?

(附注:我结束了不需要这一code,因为我发现,对比较空int值的时候,你只需要使用的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)

推荐答案

您可以将拉姆达前pression转换为特定的目标委托类型,但为了确定条件前pression的类型,编译器需要知道每个第二和第三操作数的类型。虽然他们俩都只是拉姆达前pression有没有从一个到另一个转换,所以编译器不能做任何有用的东西。

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前pression执行转换。

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

这篇关于lambda表达式和条件运算符,奇怪的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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