【发布时间】:2016-11-05 08:26:42
【问题描述】:
让我们编写这样的代码(App.xaml.xs 的片段):
public class MethodClass
{
public async Task Job()
{
Debug.WriteLine("Doing some sob");
await Task.Delay(1);
}
}
public MethodClass MyClass = null;
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
await MyClass?.Job(); // here goes NullreferenceException
MyClass?.Job(); // works fine - does nothing
为什么 Elvis 运算符不能与 async-await 一起使用?我错过了什么吗?
【问题讨论】:
-
你确定
MyClass?.Job(); // works fine?它只是什么都不做而不抛出异常 -
因为你的方法 Job 抛出异常
-
将 Job 定义为 async 并在方法内等待
-
我想这是因为你实际上是在写
await null -
因为 await MyClass?.Job() 将在 await 为空时被消耗。它会抛出异常。
标签: c# windows async-await uwp c#-6.0