Object Equals - whats the basic logic for pure objects or reference types that don't override Equals?

后端 未结 3 620
广开言路
广开言路 2021-02-14 02:03

I got here after reading this and I didn\'t find a relevant answer - So please don\'t mark this as a duplicate until you read the whole question.

I\'ve been using a refl

3条回答
  •  迷失自我
    2021-02-14 02:35

    Object.Equals is virtual. Types override it to have different behaviour.

    The default implementation, as you note, calls to an MethodImplOptions.InternalCall method (ie. it is part of the .NET runtime's internals). This method performs reference equality by directly looking at the reference (essentially it does a C/C++ pointer comparison).

    There is no recursion.

    NB. The documentation for ReferenceHelper.Equals says:

    true if the o1 parameter is the same instance as the o2 parameter, or if both are null, or if o1.Equals(o2) returns true; otherwise, false.

    (Emphasis from the source.)

    But this would imply that a.Equals(b) where Object.ReferenceEquals(a, b) is false and neither are null, then Object.Equals(object) calls ReferenceHelper.Equals(object, object) calls Object.Equals(object), …. This seems to be a documentation error (runtime behaviour is not recursive for types not overriding Equals(object) and then called for different objects resulting in a false reference equality result).

提交回复
热议问题