When can a == b be false and a.Equals(b) true?

后端 未结 7 1790
离开以前
离开以前 2021-02-01 04:59

I ran into this situation today. I have an object which I\'m testing for equality; the Create() method returns a subclass implementation of MyObject.

MyObject         


        
7条回答
  •  终归单人心
    2021-02-01 05:17

    You pretty much answered your question yourself:

    I have also over-ridden Equals() in the subclass implementation, which does a very basic check to see whether or not the passed-in object is null and is of the subclass's type. If both those conditions are met, the objects are deemed to be equal.

    The == operator hasn't been overloaded - so it's returning false since a and b are different objects. But a.Equals is calling your override, which is presumably returning true because neither a nor b are null, and they're both of the subclass' type.

    So your question was "When can a == b be false and a.Equals(b) true?" Your answer in this case is: when you explicitly code it to be so!

提交回复
热议问题