使用C#8,Visual 2019 16.7.2,给定以下C#代码:
#nullable enable
public async Task<string> GetStringAsync(); ...
public async void Main()
{
var theString = await GetStringAsync();
...
}在theString上悬停的智能感知显示了局部变量(string?)的工具提示。theString
我的GetStringAsync方法从不返回可空字符串,但变量被推断为可空。
这是一个智能感知错误吗?或者,由于theString的某些工作方式,await实际上可能为null,这是否存在更深层次的问题呢?
发布于 2020-08-25 15:23:55
这是设计出来的,与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;
}
}编译器将使用流分析来确定变量在任何给定点上是否为null。你可以在这里读到更多关于这个决定的内容。
https://stackoverflow.com/questions/63578257
复制相似问题