带有空条件运算符和等待的 C# 错误 [英] C# Error with null-conditional operator and await

查看:69
本文介绍了带有空条件运算符和等待的 C# 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中使用新的空条件运算符时遇到了一个有趣的 System.NullReferenceException.如果MyObject"为空,以下代码给我一个 NullReferenceException:

await this.MyObject?.MyMethod()

如果MyObject"为空,我原以为不会调用MyMethod",或者我误解了空条件运算符的用途?

解决方案

您可以添加 ?? 运算符,因此如果 ?. 返回空任务,请改用 CompletedTask.

await (this.MyObject?.MyMethod() ?? Task.CompletedTask)

<块引用>

如果MyObject"为空,我原以为不会调用MyMethod".

没错.?. 运算符返回空任务而不是调用 MyMethod.出现空引用异常是因为您不能等待空任务.任务必须被初始化.

I'm experiencing an interesting System.NullReferenceException whilst using the new null-conditional operator in C#. The following code gives me a NullReferenceException if "MyObject" is null:

await this.MyObject?.MyMethod()

I would've expected that the call to "MyMethod" would simply not be made if "MyObject" is null, or am I misunderstanding the purpose of the null-conditional operator?

解决方案

You can add ?? Operator so if ?. returns null task use CompletedTask instead.

await (this.MyObject?.MyMethod() ?? Task.CompletedTask)

I would've expected that the call to "MyMethod" would simply not be made if "MyObject" is null.

Thats true. the ?. operator returns null task instead of calling MyMethod. the null reference exception is made because you cant await on null task. The task must be initialized.

这篇关于带有空条件运算符和等待的 C# 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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