简体   繁体   English

空条件运算符和LINQ

[英]Null conditional operator and LINQ

There is my code (it is used in net core project): 有我的代码(它用于网络核心项目):

 var list = await user.RelatedEntityCanBeNull?.ToListAsync();

It throws NullReferenceException if RelatedEntityCanBeNull is null for user. 如果UserE的RelatedEntityCanBeNull为null,则抛出NullReferenceException。 Why doesn't the expression return null? 为什么表达式不返回null?

The await operator expects an awaitable Task object. await运算符期望一个等待的Task对象。 The Null conditional operator returns null and await null results in a NullReferenceException . Null条件运算符返回nullawait null导致NullReferenceException

You have to change your code to 您必须将代码更改为

List list = null;
if (user?.RelatedEntityCanBeNull != null)
   list = await user.RelatedEntityCanBeNull.ToListAsync();

or 要么

var list = user?.RelatedEntityCanBeNull == null ? null : await user.RelatedEntityCanBeNull.ToListAsync();

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

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