为什么我不能在 lambda 表达式中使用空传播运算符? [英] Why can't I use the null propagation operator in lambda expressions?

查看:46
本文介绍了为什么我不能在 lambda 表达式中使用空传播运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在我的代码中使用空值传播运算符,因为它使我的代码更具可读性,特别是在长查询中,我不必对每个使用的类进行空值检查.

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.

下面的代码抛出一个编译错误,我们不能在 lambda 中使用空传播运算符.

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);

错误:

错误 CS8072 表达式树 lambda 可能不包含空传播运算符.

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 种解决方案:NullPropagationExpressionConditionalExpression &混合体

You can go deeper in the relevant discussion on CodePlex where 3 solutions are offered: NullPropagationExpression, ConditionalExpression & a hybrid

这篇关于为什么我不能在 lambda 表达式中使用空传播运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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