为什么 is type / is var 对 null 产生不同的结果?
Why does is type / is var yield different results for null?
理论题:如果你使用构造
if (someVar is object o) {
然后你为 someVar
输入 null
,结果将是错误的。另一方面,如果您使用
if (someVar is var o) {
结果会是真的。为什么会这样?
完整的测试代码:
object obj = null;
if (obj is object o) {
"object".Dump();
o.Dump();
}
if (obj is var o2)
{
"var".Dump();
o2.Dump();
}
LinqPad 中的结果:
var
null
简单回答:因为 is object
被指定为包含隐式空检查,但 is var
被指定为不包含。
我能找到的最好的文档 is here(尽管它专门针对 switch 语句,而不是 if 语句):
The introduction of var as one of the match expressions introduces new rules to the pattern match.
The first rule is that the var declaration follows the normal type inference rules: The type is inferred to be the static type of the switch expression. From that rule, the type always matches.
The second rule is that a var declaration doesn't have the null check that other type pattern expressions include. That means the variable may be null, and a null check is necessary in that case.
我不能说我理解这个 (IMO) 稍微奇怪的决定背后的原因...
正如@Camilo 在评论中指出的那样,this article contains some more details. 也有很多细节。
理论题:如果你使用构造
if (someVar is object o) {
然后你为 someVar
输入 null
,结果将是错误的。另一方面,如果您使用
if (someVar is var o) {
结果会是真的。为什么会这样?
完整的测试代码:
object obj = null;
if (obj is object o) {
"object".Dump();
o.Dump();
}
if (obj is var o2)
{
"var".Dump();
o2.Dump();
}
LinqPad 中的结果:
var
null
简单回答:因为 is object
被指定为包含隐式空检查,但 is var
被指定为不包含。
我能找到的最好的文档 is here(尽管它专门针对 switch 语句,而不是 if 语句):
The introduction of var as one of the match expressions introduces new rules to the pattern match.
The first rule is that the var declaration follows the normal type inference rules: The type is inferred to be the static type of the switch expression. From that rule, the type always matches.
The second rule is that a var declaration doesn't have the null check that other type pattern expressions include. That means the variable may be null, and a null check is necessary in that case.
我不能说我理解这个 (IMO) 稍微奇怪的决定背后的原因...
正如@Camilo 在评论中指出的那样,this article contains some more details.