带有空条件运算符和等待的 C# 错误 [英] C# Error with null-conditional operator and await
问题描述
我在 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屋!