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

前端 未结 9 2194
无人及你
无人及你 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:28

    Two of the most often used types, String and Int32, implement both operator==() and Equals() as value equality (instead of reference equality). I think one can consider these two defining examples, so my conclusion is that both have identical meanings. If Microsoft states otherwise, I think they are intentionally causing confusion.

    0 讨论(0)
  • 2020-11-28 23:37
    string x = "hello";
    string y = String.Copy(x);
    string z = "hello";
    

    To test if x points to the same object as y:

    (object)x == (object)y  // false
    x.ReferenceEquals(y)    // false
    x.ReferenceEquals(z)    // true (because x and z are both constants they
                            //       will point to the same location in memory)
    

    To test if x has the same string value as y:

    x == y        // true
    x == z        // true
    x.Equals(y)   // true
    y == "hello"  // true
    

    Note that this is different to Java. In Java the == operator is not overloaded so a common mistake in Java is:

    y == "hello"  // false (y is not the same object as "hello")
    

    For string comparison in Java you need to always use .equals()

    y.equals("hello")  // true
    
    0 讨论(0)
  • 2020-11-28 23:38

    My understanding of the uses of both was this: use == for conceptual equality (in context, do these two arguments mean the same thing?), and .Equals for concrete equality (are these two arguments in actual fact the exact same object?).

    Edit: Kevin Sheffield's linked article does a better job of explaining value vs. reference equality…

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