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

后端 未结 7 1761
离开以前
离开以前 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:19

    The "==" operate tests absolute equality (unless overloaded); that is, it tests whether two objects are the same object. That's only true if you assigned one to the other, ie.

    MyObject a = MyObject.Create();
    MyObject b = a;
    

    Just setting all the properties of two objects equal doesn't mean the objects themselves are. Under the hood, what the "==" operator is comparing is the addresses of the objects in memory. A practical effect of this is that if two objects are truly equal, changing a property on one of them will also change it on the other, whereas if they're only similar ("Equals" equal), it won't. This is perfectly consistent once you understand the principle.

提交回复
热议问题