不能使用三元运算符来分配LINQ表达式 [英] Can't use ternary operator to assign Linq expression

查看:929
本文介绍了不能使用三元运算符来分配LINQ表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚键入下面的代码:

Expression<Func<ContentItem, bool>> expression = 
                fileTypeGroupID.HasValue ? n => n.Document.MimeType.FileTypeGroupID == fileTypeGroupID.Value : n => true;



Visual Studio是说,它不能推断出 N

中的代码看起来没什么问题 - 它只是使用三元运算符来分配两个表达式文字到表达式变量。

The code seems fine to me - it's just using a ternary operator to assign one of two Expression literals to an Expression variable.

时的Visual Studio只是没有足够的智慧来推断的类型 N 三元运营商里面,还是我做一些错误的?

Is Visual Studio just not smart enough to infer the type of n inside a ternary operator, or have I made some kind of mistake?

推荐答案

此问题是几乎每天都要求某种形式的。

This question is asked almost every day in some form.

条件运算类型的分析,从 ,不是的里外的到的>。有条件的经营者不知道的什么类型的结果被分配的,然后的胁迫的后果和替代这些类型的。这则相反;它的工作原理出类型的结果和替代的,作为更一般的这两种类型的,然后验证该一般类型可以被分配

The conditional operator type analysis proceeds from inside to outside, not outside to inside. The conditional operator does not know to what type its results are being assigned and then coerces the consequence and alternative to those types. It does the opposite; it works out the types of the consequence and alternative, takes the more general of those two types, and then verifies that the general type may be assigned.

的后果和替代不包含有关拉姆达的类型应该是什么样的信息,因此,有条件的类型不能推断。因此它不能验证该指派是正确的。

The consequence and alternative contain no information about what the type of the lambda should be, and therefore the type of the conditional cannot be inferred. Therefore it cannot be verified that the assignment is correct.

据启发性的考虑为何语言被设计的方式。假设你有重载:

It is edifying to consider why the language was designed that way. Suppose you have overloads:

 void M(Func<string, int> f) {}
 void M(Func<double, double> f) {}

和通话

M( b ? n=>n.Foo() : n => n.Bar() );



描述重载解析如何确定其中M超载选择在类型从外部推断的世界。在

Describe how overload resolution determines which overload of M is chosen in a world where types are inferred from outside to inside.

现在看看这个例子:

M( b1 ? (b2 ? n=>n.Foo() : n => n.Bar() ) : (b3 ? n=>n.Blah() : n=>n.Abc()) );



越来越难,不是吗?现在想象一下,美孚,酒吧,胡说和ABC是他们自己的方法了funcs中,也有含lambda表达式有条件的经营者的论点。

Getting harder isn't it? Now imagine that Foo, Bar, Blah and Abc were themselves methods that took funcs, and also had arguments with conditional operators containing lambdas.

我们不希望做的类型推理过程如此复杂,没有相应的巨大的利益,并没有为条件运算符没有这样巨大的利益。

We do not wish to make the type inference process so complex without a corresponding huge benefit, and there is no such huge benefit for the conditional operator.

你应该在你的情况做的就是投的后果和替代特定类型的一个或两个。

What you should do in your case is cast one or both of the consequence and alternative to the specific type.

这篇关于不能使用三元运算符来分配LINQ表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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