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

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

    The key difference between == and Equals is that == (like all operators) is not polymorphic, while Equals (like any virtual function) is.

    By default, reference types will get identical results for == and Equals, because they both compare references. It's also certainly possible to code your operator logic and Equals logic entirely differently, though that seems nonsensical to do. The biggest gotcha comes when using the == (or any) operator at a higher level than the desired logic is declared (in other words, referencing the object as a parent class that either doesn't explicitly define the operator or defines it differently than the true class). In such cases the logic for the class that it's referenced as is used for operators, but the logic for Equals comes from whatever class the object actually is.

    I want to state emphatically that, based solely upon the information in your question, there is absolutely no reason to think or assume that Equals compares values versus references. It's trivially easy to create such a class, but this is not a language specification.

    Post-question-edit edit

    Your implementation of Equals will return true for any non-null instance of your class. Though the syntax makes me think that you aren't, you may be confusing the is C# keyword (which confirms type) with the is keyword in VB.NET (which confirms referential equality). If that is indeed the case, then you can make an explicit reference comparison in C# by using Object.ReferenceEquals(this, obj).

    In any case, this is why you are seeing true for Equals, since you're passing in a non-null instance of your class.

    Incidentally, your comment about NUnit using Equals is true for the same reason; because operators are not polymorphic, there would be no way for a particular class to define custom equality behavior if the Assert function used ==.

    0 讨论(0)
提交回复
热议问题