== vs. Object.Equals(object) in .NET

前端 未结 9 2240
无人及你
无人及你 2020-11-28 22:33

So, when I was a comparative novice to the novice I am right now, I used to think that these two things were syntactic sugar for each other, i.e. that using one over the oth

9条回答
  •  失恋的感觉
    2020-11-28 23:27

    Microsoft says that class implementers should make == behave as similarly as possible to Equals:

    DO ensure that Object.Equals and the equality operators have exactly the same semantics

    from http://msdn.microsoft.com/en-us/library/vstudio/7h9bszxx(v=vs.110).aspx


    If you want to be certain you are getting IDENTITY comparison (when comparing references), then use ReferenceEquals instead.

    If a class implementor does not override ==, then static method is looked for, at compile time, in base classes. If this search reaches Object, then Object.== is used. For classes, this is same as ReferenceEquals.

    If class documentation is uncertain as to whether a given class (from a vendor other than Microsoft presumably) implements == as Equals or ReferenceEquals (or it could in theory be different than both of those), I sometimes avoid ==. Instead, I use the less readable Equals(a, b) or ReferenceEquals(a, b), depending on which meaning I want.

    OTOH, ps2goat makes a good point that using == avoids exception if first operand is null (because == is a static operator). This is an argument in favor of using ==.


    Removed controversial commentary regarding ==


    UPDATE A recent Microsoft doc quote, from .Net 4.7.2 retrieved Feb. 2019, shows they still intend the two to behave similarly:

    Object.Equals Method

    Some languages such as C# and Visual Basic support operator overloading. When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. This is typically accomplished by writing the Equals(Object) method in terms of the overloaded equality operator, as in the following example.


    NOTE: See other answers for the consequences of == being a static method vs Equals being an instance method. I'm not claiming behavior is identical; I'm observing that Microsoft recommends making the two as similar as possible.

提交回复
热议问题