When should I use ==? When should I use Equals?

zhaozj2021-02-12  173

When should I use ==? When should I use Equals?

The equals method is just a virtual method defined in System.Object, which is rewritten by any class that selects the task. == The operator is an operator that can be overloaded by class, which usually has constant behavior.

For reference types that are not overloaded ==, the operator compares whether the two reference types are referenced to the same object, and this is exactly the work made by the Equals implementation in System.Object.

For value types that are not overloaded ==, the operator compares whether these two values ​​are "bit" equal, that is, whether each of these two values ​​is equal. This situation will still happen when you call Equals to the value type, but this time, this implementation is provided by valueetype and compares to the reflection, so that the comparison speed is much slower than the type.

So far, the two are so similar. The main difference between the two is polymorphism. The operator is overloaded instead of being rewritten, which means that it is only called constant version unless the compiler knows the more specific version. To clarify this, please see the example below:

Using System; Public Class Test {Static Void Main () {// Create Two Equal But Distinct Strings String A = New String (New Char [] {'h', 'E', 'L', 'L', 'O '}); string b = new string (new char [] {' h ',' e ',' L ',' L ',' o '}); console.writeline (a == b); console.writeline (a.Equals (b)); // Now let's see what happens with the Same tests but // // of variables of type object Object C = a; Object D = B; console.writeLine (c == d); console. WriteLine (C. Equals (D));}}

turn out:

Truetruefalsetrue

The third line is False because the compiler does not know that the contents of C and D are string references, so it can only call == non-overloaded versions. Because they are references to different strings, the constant operator returns false.

So, how should I use these operators? My criterion is: For almost all reference types, use Equals when you want to test equality rather than reference consistency. The case is a string - use == Comparison string does make more simple things, and the code readability is better, but you need to remember that both ends of the operator must be type string expressions, The comparative is normal.

For value type, I usually use ==, because unrecorded type itself contains reference types (this is extremely rare), it is constant to equal or equal problems.

[Author: Jon Skeet]

Published: March 29, 2004 15:56:00 GMT Monday

转载请注明原文地址:https://www.9cbs.com/read-7160.html

New Post(0)