在 Jon Skeet 的 C# 6 帖子中,标题为 Clean Event Handlers Invocation with C# 6他展示了您现在可以如何编写
public void OnFoo()
{
Foo?.Invoke(this, EventArgs.Empty);
}
代替
public void OnFoo()
{
EventHandler handler = Foo;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
如果我们谈论的是可等待的方法,有什么方法可以做这样的单行代码吗?如果我尝试
await Foo?.Invoke();
我得到以下编译错误:
The awaiter type
System.Runtime.CompilerServices.TaskAwaiter?
must have suitableIsCompleted
andGetResult
members (CS4011).
注意:我使用的是 Mono(适用于 OSX v5.9.5 的 Xamarin Studio),因此编译器结果可能与使用 Visual Studio 时的结果不同。
最佳答案
@i3arnon 有一个很好的解决方案,但是这是您可以不需要添加字段或属性的另一种方法。
await (Foo?.Invoke() ?? Task.CompletedTask);
或者如果Task<T>
var i = await (Foo?.Invoke() ?? Task.FromResult<T>(default(T)))
关于c# - 使用 C# 6 为可等待方法调用一行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32079218/