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?
这是设计使然,与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)
编译器将使用流分析来确定变量在任何给定点是否为空。您可以在此处阅读有关该决定的更多信息。
| 归档时间: |
|
| 查看次数: |
252 次 |
| 最近记录: |