Object.Equals(obj,null)和obj == null有什么区别

Object.Equals(obj,null)和obj == null有什么区别

问题描述:

几乎每次我想将对象的相等性检查为 null 时,我都会使用常规的相等性检查操作

Almost every time I want to check object's equality to null I use the normal equality check operation

if (obj == null)

最近我发现我更频繁地使用 Object.Equals()

Recently I noticed that I'm using the Object.Equals() more often

if (Object.Equals(obj, null))

,并且在阅读有关null检查的内容时,我发现此 Is ReferenceEquals(null,obj)与null == obj一样吗?

and while reading about null checking I fount this Is ReferenceEquals(null, obj) the same thing as null == obj?

if (ReferenceEquals(null, obj))

有什么区别?以及在哪里/何时使用每一个?另外我发现,根据它们的 summary

Whats the difference? and where/when to use each one? plus I found that the last two checks look like the same according to their summary

Object.Equals(x,y)将:

  • 如果 x y 都为空,则返回true
  • 如果 x y 中的一个恰好为空,则返回false
  • 否则调用 x.Equals(y) y.Equals(x)-没什么关系.这意味着将调用对象 x y execution-time 类型实现的任何多态行为.
  • Return true if x and y are both null
  • Return false if exactly one of x or y is null
  • Otherwise call either x.Equals(y) or y.Equals(x) - it shouldn't matter which. This means that whatever polymorphic behaviour has been implemented by the execution-time type of the object x or y refers to will be invoked.

ReferenceEquals 调用多态的 Equals 方法.它 just 比较引用是否相等.例如:

ReferenceEquals will not call the polymorphic Equals method. It just compares references for equality. For example:

string x = new StringBuilder("hello").ToString();
string y = new StringBuilder("hello").ToString();
Console.WriteLine(Object.Equals(x, y)); // True
Console.WriteLine(Object.ReferenceEquals(x, y)); // False
Console.WriteLine(x == y); // True due to overloading

现在,如果仅 检查是否为空,那么您实际上就不会想要这种多态行为-只需引用相等性即可.因此,请随时使用 ReferenceEquals .

Now if you're only checking for nullity, then you don't really want the polymorphic behaviour - just reference equality. So feel free to use ReferenceEquals.

您也可以 使用 == ,但是可以由类重载(不覆盖)-在字符串的情况下,如上所示.根据我的经验,使用 ReferenceEquals 的最常见情况是实施 == :

You could also use ==, but that can be overloaded (not overridden) by classes - it is in the case of string, as shown above. The most common case for using ReferenceEquals in my experience is when you're implementing ==:

public bool operator ==(Foo x1, Foo x2)
{
    if (ReferenceEquals(x1, x2))
    {
        return true;
    }
    if (ReferenceEquals(x1, null) || ReferenceEquals(x2, null))
    {
        return false;
    }
    return x1.Equals(x2);
}

在这里,您真的不想调用 == 实现,因为它会永远递归-您需要非常明确的引用相等语义.

Here you really don't want to call the == implementation, because it would recurse forever - you want the very definite reference equality semantics.