为什么 C# 中的 async/await 即使被告知不要返回可空值?

Ori*_*rds 6 c# visual-studio async-await nullable-reference-types

使用 C#8,Visual Studio 2019 16.7.2,给出以下 C# 代码:

#nullable enable

public async Task<string> GetStringAsync(); ...

public async void Main()
{
    var theString = await GetStringAsync();
    ...
}
Run Code Online (Sandbox Code Playgroud)

悬停在上面的智能感知theString显示局部变量(字符串?)theString的工具提示

我的GetStringAsync方法从不返回可为空的字符串,但该变量被推断为可为空的。

这是一个智能感知错误吗?或者是否有更深层次的事情theString由于某种有效的方式实际上可以为空await

Pat*_*vid 5

这是设计使然,与await.

var始终可以为空,从规范

var推断引用类型的注释类型。例如,在var s = "";var被推断为string?

因此,theString当您使用var. 如果您希望它不可为空,请string显式使用。


至于为什么:简而言之,就是允许这样的场景:

#nullable enable

public async Task<string> GetStringAsync(); ...

public async void Main()
{
    var theString = await GetStringAsync();
    
    if (someCondition)
    {
        // If var inferred "string" instead of "string?" the following line would cause
        // warning CS8600: Converting null literal or possible null value to non-nullable type.
        theString = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器将使用流分析来确定变量在任何给定点是否为空。您可以在此处阅读有关该决定的更多信息。

  • 谢谢!我不知道 `var` 总是可以为空的。很有道理,我想我走错了路,认为它与异步有某种关系 (2认同)
  • 奇怪的。您可能会认为,如果您想稍后分配 null,则必须改为编写 var theString = (string?) (await ....) 。 (2认同)