简体   繁体   English

为什么我不能在 lambda 表达式中使用空传播运算符?

[英]Why can't I use the null propagation operator in lambda expressions?

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.我经常在我的代码中使用空传播运算符,因为它为我提供了更具可读性的代码,特别是在长查询中,我不必对每个使用的类进行空检查。

The following code throws a compile error that we can't use null propagating operator in lambda.下面的代码抛出一个编译错误,我们不能在 lambda 中使用空传播运算符。

var cnt = humans.AsQueryable().Count(a => a.House?[0].Price == 5000);

The error :错误 :

Error CS8072 An expression tree lambda may not contain a null propagating operator.错误 CS8072 表达式树 lambda 可能不包含空传播运算符。

C# Could easily translate above code to the code to following code if really can't do anything else!如果真的不能做任何其他事情,C# 可以很容易地将上面的代码转换为下面的代码!

var cnt = humans.AsQueryable().Count(a => a.House != null && a.House[0].Price == 5000);

I'm curious why C# does nothing and simply throws a compiler error?我很好奇为什么 C# 什么都不做,只是抛出一个编译器错误?

It's complicated since expression tree lambdas (unlike delegate lambdas) are interpreted by already existing LINQ providers which don't yet support null propagating.这很复杂,因为表达式树 lambda(与委托 lambda 不同)由尚不支持空值传播的现有 LINQ 提供程序解释。

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

You can go deeper in the relevant discussion on CodePlex where 3 solutions are offered: NullPropagationExpression , ConditionalExpression & a hybrid您可以深入了解 CodePlex的相关讨论,其中提供了 3 种解决方案: NullPropagationExpressionConditionalExpression和混合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM