C#: How does the static object.Equals check for equality?

ぐ巨炮叔叔 提交于 2019-12-30 02:42:12

问题


Say you have two different classes where each have their own implementation of Equals; which one is used? What if only one of them have one? Or none of them? Are any of the following lines equivalent?

object .Equals( first, second )
first .Equals( second )
second .Equals( first )

I'm guessing that the first two might be equivalent, but I don't really have a clue.

What does it really do?


回答1:


Basically it does three things:

  • Check for reference equality (return true if so)
  • Check for reference nullity (return false if either value is null; by now the null == null case has been handled)
  • Check for value equality with first.Equals(second)

The ordering shouldn't matter if both values have well-behaved equality implementations, as equality should be implemented such that x.Equals(y) implies y.Equals(x). However, the offline documentation I've got installed does state that first.Equals(second) (or objA.equals(objB) to use the real parameter naming) is specified. The online documentation doesn't mention this, interestingly enough.

Just to make all of this concrete, the implementation could look like this:

public static bool Equals(object x, object y)
{
    if (x == y) // Reference equality only; overloaded operators are ignored
    {
        return true;
    }
    if (x == null || y == null) // Again, reference checks
    {
        return false;
    }
    return x.Equals(y); // Safe as we know x != null.
}



回答2:


By default, object equivalency is determined by the object's address in memory. If both instances have the same memory address, they are equal.

However, this can be overloaded within the object so that developers can compare two objects that arn't in the same memory location and still be considered equal. For example, if you had a Data Access Layer where each object had its data record's ID from the database, you could have object equality compared based on the ID.

You can overload operators to produce this functionality.



来源:https://stackoverflow.com/questions/1451454/c-how-does-the-static-object-equals-check-for-equality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!