模式匹配等于null与null [英] Pattern matching equal null vs is null

查看:51
本文介绍了模式匹配等于null与null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Microsoft new-features-in-c-7-0:

From Microsoft new-features-in-c-7-0:

public void PrintStars(object o)
{
    if (o is null) return;     // constant pattern "null"
    if (!(o is int i)) return; // type pattern "int i"
    WriteLine(new string('*', i));
}

o == null o is null 的区别是什么?

推荐答案

o为空转换为 object.Equals(null,o)(您可以看到它这里).

The o is null is translated to object.Equals(null, o) (you can see it here).

object.Equals 代码编写为:

public static bool Equals(Object objA, Object objB)
{
    if (objA == objB)
    {
        return true;
    }
    if (objA == null || objB == null)
    {
        return false;
    }
    return objA.Equals(objB);
}

因此最后会有一个 o == null (第一个 if ).请注意, System.Object 没有定义 operator == ,因此所使用的一种是用于引用类型的引用,即引用相等.

so in the end there will be a o == null (the first if). Note that System.Object doesn't define the operator==, so the one used is the one for reference types that is reference equality.

从理论上讲,通过观看被调用的代码,可以认为应该将 o == null (使用 o System.Object )比 o null为空(更少的操作)要快...但是谁知道呢?:-)

Theorically, by watching the called code, one could think that o == null (with o a System.Object) should be faster than o is null (less operations)... But who knows? :-)

最终结果是,通过两种不同的途径, o为null o == null (其中 o System.Object )返回相同的结果.

The end result is that, through two different routes, o is null and o == null (with o a System.Object) return the same result.

通过查看,我们甚至可以看到 o == null object.ReferenceEquals(o,null)(带有 o System.Object ):-).

By looking we can even see that o == null is the same as object.ReferenceEquals(o, null) (with o a System.Object) :-).

有趣的问题应该是,C#编译器为什么不将 x为null 转换为 object.ReferenceEquals(x,null)?.请注意,由于可空类型的装箱是如何完成的,因此即使在以下情况下也可以使用

the interesting question should be, why doesn't the C# compiler translates the x is null to object.ReferenceEquals(x, null)?. Note that, thanks to how the boxing of nullable types is done, it would work even for:

int? a = null;
if (a is null) { /* */ }

对编译器的更改使此响应无效...如果单击此处"链接,则可以看到它

这篇关于模式匹配等于null与null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆