【发布时间】:2021-09-02 20:29:17
【问题描述】:
如何将Task<string> 实例用作方法的Task
如果我启用了可空性,并且我有两个异步方法,例如..
// in an ordinary class
public async static Task<string> Foo() { ... }
// in a static class
public async static Task Bar(this Task<string?> task1) { ... }
我尝试调用await Foo().Bar();,但编译器给了我:
warning CS8620: Argument of type 'Task<string>' cannot be used for parameter 'task' of type 'Task<string?>'
我可以对 Foo 的结果做些什么来使它可以作为一个 Task
【问题讨论】:
-
我想你正在寻找! (null-forgiving) operator
-
@patrick-szalapski 你可以这样使用它:
await FooClass.Foo()!.Bar(); -
谢谢,但我不明白。 Foo() 不返回可空任务(它返回
Task<string>,而不是Task<string>?);为什么我需要在不可为空的东西上原谅 null?
标签: c# generics nullable nullable-reference-types