Overloading operator== versus Equals()

前端 未结 6 833
生来不讨喜
生来不讨喜 2020-11-29 20:46

I\'m working on a C# project on which, until now, I\'ve used immutable objects and factories to ensure that objects of type Foo can always be compared for equal

6条回答
  •  一整个雨季
    2020-11-29 21:16

    There's a big difference between overloading == and overriding Equals.

    When you have the expression

    if (x == y) {
    

    The method that will be used to compare variables x and y is decided at compile time. This is operator overloading. The type used when declaring x and y is used to define which method is used to compare them. The actual type within x and y (i.e., a subclass or interface implementation) is irrelevant. Consider the following.

    object x = "hello";
    object y = 'h' + "ello"; // ensure it's a different reference
    
    if (x == y) { // evaluates to FALSE
    

    and the following

    string x = "hello";
    string y = 'h' + "ello"; // ensure it's a different reference
    
    if (x == y) { // evaluates to TRUE
    

    This demonstrates that the type used to declare the variables x and y is used to determine which method is used to evaluate ==.

    By comparison, Equals is determined at runtime based on the actual type within the variable x. Equals is a virtual method on Object that other types can, and do, override. Therefore the following two examples both evaluate to true.

    object x = "hello";
    object y = 'h' + "ello"; // ensure it's a different reference
    
    if (x.Equals(y)) { // evaluates to TRUE
    

    and the following

    string x = "hello";
    string y = 'h' + "ello"; // ensure it's a different reference
    
    if (x.Equals(y)) { // also evaluates to TRUE
    

提交回复
热议问题