bur*_*huy 7 c# exception nullreferenceexception async-await null-propagation-operator
我有以下代码:
await _user?.DisposeAsync();
Run Code Online (Sandbox Code Playgroud)
Visual Studio 突出显示此代码,说“可能的 NullReferenceException”
顺便说一句,没有await Visual Studio不显示此警告为什么NullReferenceException在这里可能?
can*_*on7 10
await null会抛出一个NullReferenceException. 因此,如果_user为空,_user?.DisposeAsync()则将返回null,并且await将抛出。
你可以做:
if (_user != null)
{
await _user.DisposeAsync();
}
Run Code Online (Sandbox Code Playgroud)
(_user如果它可能在读取之间发生变化,您可能需要一个本地副本)
或者:
await _user?.DisposeAsync().AsTask() ?? Task.CompletedTask;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |