未从 FirstOrDefault 公开的可空引用类型信息
Nullable reference type information not exposed from FirstOrDefault
我想测试 C# 8.0 中的新 nullable reference types 功能。
我开始了一个针对 .NET Core 3.0 的新项目,在 .csproj
文件中启用了可为 null 的引用类型,并开始编码。我创建了一个简单的列表,它采用 string[]
和 return 数组中等于 abc
的 string
。现在,因为我不确定 abc
是否确实存在于数组中,所以我使用 FirstOrDefault()
,如果找不到匹配项,它应该默认为 null
。
using System;
using System.Linq;
public string FindArgument(string[] args)
{
var arg = args.FirstOrDefault(x => x == "abc");
return arg;
}
我的方法returns string
,应该现在是不可空类型。由于 FirstOrDefault()
可能 return null
,我希望上述方法在 returning maybe null arg
变量。它没有。
查看 Visual Studio 中 FirstOrDefault()
的签名,很清楚为什么 :方法 returns a string
,而不是我期望的可为 null 的等价物 string?
。
使用下面的方法主体确实会产生我预期的警告:
var arg = args.Contains("abc") ? "abc" : null;
return arg;
当面向 .NET Core 3.0 时,系统库(在此示例中 System.Linq
)是否真的不公开可空性信息?
看起来 System.Linq
在 3.0 版本中不可为空注释。所以 Nullable Reference Types 不会发出正确的警告。
你可以查一下类似的问题roslyn repo. This open issue on Github和你的问题很相似。在那一期中,贡献者解释了当前的问题:
System.Linq
is nullable annotated in master branch of corefx, but not in release/3.0. So there's nothing unexpected in compiler.
The compiler should provide some diagnostics showing that you are using nullable-oblivious stuff.
我想测试 C# 8.0 中的新 nullable reference types 功能。
我开始了一个针对 .NET Core 3.0 的新项目,在 .csproj
文件中启用了可为 null 的引用类型,并开始编码。我创建了一个简单的列表,它采用 string[]
和 return 数组中等于 abc
的 string
。现在,因为我不确定 abc
是否确实存在于数组中,所以我使用 FirstOrDefault()
,如果找不到匹配项,它应该默认为 null
。
using System;
using System.Linq;
public string FindArgument(string[] args)
{
var arg = args.FirstOrDefault(x => x == "abc");
return arg;
}
我的方法returns string
,应该现在是不可空类型。由于 FirstOrDefault()
可能 return null
,我希望上述方法在 returning maybe null arg
变量。它没有。
查看 Visual Studio 中 FirstOrDefault()
的签名,很清楚为什么 :方法 returns a string
,而不是我期望的可为 null 的等价物 string?
。
使用下面的方法主体确实会产生我预期的警告:
var arg = args.Contains("abc") ? "abc" : null;
return arg;
当面向 .NET Core 3.0 时,系统库(在此示例中 System.Linq
)是否真的不公开可空性信息?
看起来 System.Linq
在 3.0 版本中不可为空注释。所以 Nullable Reference Types 不会发出正确的警告。
你可以查一下类似的问题roslyn repo. This open issue on Github和你的问题很相似。在那一期中,贡献者解释了当前的问题:
System.Linq
is nullable annotated in master branch of corefx, but not in release/3.0. So there's nothing unexpected in compiler. The compiler should provide some diagnostics showing that you are using nullable-oblivious stuff.