c# - 使用 C# 6 为可等待方法调用一行方法?

标签 c# mono async-await c#-6.0

在 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 suitable IsCompleted and GetResult 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/

相关文章:

javascript - 如何回调 async/await 函数

c# - 使用 Linq 求和嵌套值

c# - 从 C# 方法返回方法

c# - 一次单击 2 个按钮

mono - 人们在 Mono/MonoDevelop 中使用什么 BDD 框架

c# - 如何实时读取输出并在需要时在特定时间停止

c# - 为什么仅在实现接口(interface)后才重写方法?

c# - 试图避免 AppDomains

node.js - async/await 不等待返回值

javascript - Node : Confusing behaviour related to saving a TypeORM model using await inside a callback/promises clearing