编程语言
首页 > 编程语言> > c#-为什么类型/ var对于null会产生不同的结果?

c#-为什么类型/ var对于null会产生不同的结果?

作者:互联网

这个问题已经在这里有了答案:            >            What’s the benefit of var patterns in C#7?                                    4个
>            Usage of Var Pattern in C# 7                                    2个
理论问题:如果使用构造

if (someVar is object o) {

并且您为someVar输入了null,结果将为false.另一方面,如果您使用

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对象被指定为包含隐式null检查,而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包含更多详细信息. This question thread也有很多细节.

标签:c-7-0,c
来源: https://codeday.me/bug/20191024/1922665.html