为什么编译器不在第 3 行警告我?实际上它试图说服我 Id 永远不会为空。第 2 行有一个警告。
问题出现在 NSwag 生成的类/DTO 中,其中包含禁用 nullable 的
<auto-generated>
标记(此处记录https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references#nullable-contexts)
注意最后一堂课前的
#nullable disable
int CalcLength1(MyClass instance) => instance.Id.Length;
int CalcLength2(MyClassNullableId instance) => instance.Id.Length;
int CalcLength3(MyOldClass instance) => instance.Id.Length;
class MyClass
{
public string Id { get; set; } = string.Empty;
}
class MyClassNullableId
{
public string? Id { get; set; }
}
#nullable disable
class MyOldClass
{
public string Id { get; set; }
}
来自 可空引用类型 (NRT) 文档:
在禁用上下文中编译的代码中的引用类型变量是可以忽略的。 ...但是,可为空的遗忘变量的默认状态是非空。
并来自了解上下文和警告:
每个变量都有一个默认的可空状态,这取决于其可空性:
- 可空变量的默认值
为null-state
。maybe-null
- 不可为 null 的变量的默认
为null-state
l。not-nul
- 可为空的不经意变量的默认值
为null-state
。not-null
由于您已禁用
MyOldClass
的可为空上下文,因此其属性的默认状态被确定为 not-null
,因此 MyOldClassInstance.Id.Length
不会产生警告(至于为什么 - 我认为这样做是为了防止出现误报)使用未升级为使用 NRT 的库)