C# Error with null-conditional operator and await

时间秒杀一切 提交于 2019-12-06 19:04:53

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33592547/c-sharp-error-with-null-conditional-operator-and-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!