为什么我不能使用lambda表达式零传播经营者? [英] Why can't I use the null propagation operator in lambda expressions?
问题描述
我经常使用空传播经营者在我的代码,因为它给了我更多的可读的代码,特别是在长的查询,我没有为null检查所使用的每一个类。
I often use null propagating operator in my code because it gives me more readable code, specially in long queries I don't have to null-check every single class that is used.
下面的代码抛出,我们不能在拉姆达使用null传播运营编译错误。
The following code throws a compile error that we can't use null propagating operator in lambda.
var cnt = humans.AsQueryable().Count(a => a.House?[0].Price == 5000);
错误:
The error :
错误CS8072表达式树lambda不能包含null传播运营商。
Error CS8072 An expression tree lambda may not contain a null propagating operator.
C#可以很容易地转换上面的代码的代码以下面的代码,如果真的不能做任何事情!
C# Could easily translate above code to the code to following code if really can't do anything else!
var cnt = humans.AsQueryable().Count(a => a.House != null && a.House[0].Price == 5000);
我很好奇,为什么C#什么也不做,只是抛出一个编译器错误?
I'm curious why C# does nothing and simply throws a compiler error?
推荐答案
由于表达式树lambda表达式(不像委托lambda表达式)通过现有的LINQ提供解释这还不支持空传播很复杂。
It's complicated since expression tree lambdas (unlike delegate lambdas) are interpreted by already existing LINQ providers which don't yet support null propagating.
转换为条件表达式,因为有多种评估并不总是准确的,而与
这里只有例如一个评价?:
Converting to a conditional expression is not always accurate as there are multiple evaluations while with ?.
there's only a single evaluation for example:
customer.Where(a => c.Increment()?.Name) // Written by the user
customer.Where(a => c.Increment() == null ? null : c.Increment().Name) // Incorrectly interpreted by an old LINQ provider
您可以在CodePlex上相关讨论走向深入其中,3解决方案可供选择: NullPropagationExpression
,条件表达式
&安培;混合
You can go deeper in the relevant discussion on CodePlex where 3 solutions are offered: NullPropagationExpression
, ConditionalExpression
& a hybrid
这篇关于为什么我不能使用lambda表达式零传播经营者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!