Non-Nullable 在 return 上变为 Nullable
Non-Nullable becomes Nullable on return
我想我在某个地方看到过这个问题的答案,但我找不到,也不记得答案了。
假设 Nullable-Reference-Types 已启用。
有一种方法return是string
。该方法的调用者将结果字符串存储到一个变量中。即使方法的 return 值不可为空,该变量也将为 Nullable。
static string MyMethod()
{
return "Hello World!";
}
public static void Main()
{
// result is of type string? here. Hence nullable.
var result = MyMethod();
}
基本类型似乎没有发生同样的情况,但引用类型确实发生了,比如 object
。对我来说有点违背了 NRT 的目的。我敢肯定这是有原因的,而且是“设计使然”。
在 C# 8.0 中,字符串被称为可为 null 的“字符串!”,因此 Allow Null 批注允许将其设置为 null,即使我们 return 的字符串不为 null(例如,我们进行比较检查,如果为 null,则将其设置为默认值。)
这确实是设计使然。
选择此设计的会议记录如下:https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md#var
总结一下:我们发现人们经常不得不显式键入变量而不是使用 var
,因为在从 non-null-returning 方法赋值后,代码继续赋值 null
到变量。
引用会议记录:
At this point we've seen a large amount of code that requires people
spell out the type instead of using var, because code may assign null
later.
也就是发现类似下面的代码比较频繁:
var someVariable = SomeMethodThatDoesntReturnNull();
...
someVariable = null; // or someVariable = someMethodThatCanReturnNull();
请注意(正如 Jeroen Mostert 所指出的)您问题中的 result2
不可为空,因为它被显式键入为 non-nullable。我不确定您为什么认为它 是 可以为 null,但它绝对不是。
例如,查看 this repro on DotNetFiddle 并注意第 11 行的警告。
我想我在某个地方看到过这个问题的答案,但我找不到,也不记得答案了。
假设 Nullable-Reference-Types 已启用。
有一种方法return是string
。该方法的调用者将结果字符串存储到一个变量中。即使方法的 return 值不可为空,该变量也将为 Nullable。
static string MyMethod()
{
return "Hello World!";
}
public static void Main()
{
// result is of type string? here. Hence nullable.
var result = MyMethod();
}
基本类型似乎没有发生同样的情况,但引用类型确实发生了,比如 object
。对我来说有点违背了 NRT 的目的。我敢肯定这是有原因的,而且是“设计使然”。
在 C# 8.0 中,字符串被称为可为 null 的“字符串!”,因此 Allow Null 批注允许将其设置为 null,即使我们 return 的字符串不为 null(例如,我们进行比较检查,如果为 null,则将其设置为默认值。)
这确实是设计使然。
选择此设计的会议记录如下:https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md#var
总结一下:我们发现人们经常不得不显式键入变量而不是使用 var
,因为在从 non-null-returning 方法赋值后,代码继续赋值 null
到变量。
引用会议记录:
At this point we've seen a large amount of code that requires people spell out the type instead of using var, because code may assign null later.
也就是发现类似下面的代码比较频繁:
var someVariable = SomeMethodThatDoesntReturnNull();
...
someVariable = null; // or someVariable = someMethodThatCanReturnNull();
请注意(正如 Jeroen Mostert 所指出的)您问题中的 result2
不可为空,因为它被显式键入为 non-nullable。我不确定您为什么认为它 是 可以为 null,但它绝对不是。
例如,查看 this repro on DotNetFiddle 并注意第 11 行的警告。