请问空== NULL? [英] Does null == null?

查看:91
本文介绍了请问空== NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类型的对象
美孚有一个编号(INT)

I have an object of type Foo.
Foo has an Id (int)

a)是否code波纹管好?
   二)我应该回报,如果都为null?

a) Is the code bellow "good"?
b) What should I return if both are null?

// overload operator ==
public static bool operator ==(Foo a, Foo b)
{
    if (ReferenceEquals(x, y))
    {
        return true;
    }

    if (x == null && y == null)
    {
        return // ??? 
    }

    if (x == null || y == null)
    {
        return false; 
    }

    return x.Id == y.Id; // Ids are the same
}

public static bool Equals(Foo x, Foo y)
{
   return x == y;
}

编辑:
c)如果在等于方法调用的 ==操作符或反之亦然?


c) Should the Equals method call the == operator, or viceversa?

最后一个问题
D)是有可能, 的ReferenceEquals(X,Y)==真 x.Id!= y.Id

Last question
d) Is it possible that ReferenceEquals(x, y) == true AND x.Id != y.Id?

推荐答案

无非是内部指针值为零。所以它是比较具有零值的两个引用。

null is nothing but internal Pointer with value zero. So it is comparing two references having value zero.

在事实上 object.ReferenceEquals(NULL,NULL)是因为这个事实,所以你并不需要第二次检查总是如此。

In fact object.ReferenceEquals(null, null) is always true because of this fact so you do not need the second check.

if (ReferenceEquals(x, y))
{
    return true;
}

if (x == null && y == null) // THIS CHECK IS REDUNDANT!!!
{
    return true;
}

在最后一点,==和equals的处理的装箱值类型一样,除非:

On the last point, == and Equals are handled the same unless on the boxed value types:

        object s1 = 2;
        object s2 =  1+1;

        Console.WriteLine(s1 == s2);
        Console.WriteLine(s1.Equals(s2));

这会产生

d点:这是同一个对象,相同的内存空间 - 如果它们都指向一个字段的对象

Point d: NO it is the same object, the same memory space - if they are pointing to a field on the object.

这篇关于请问空== NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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