Comparison and sorting of objects (4): equality of objects to determine equals and iequatable
Source: Internet
Author: User
This section covers the following knowledge points: 1. Object. Equals () method; 2. "=", "! = "Operator overload; 3. iequatable <t> interface. 1. Rewrite the equals method. As we all know, the object type has an instance method named equals that can be used to determine whether two objects are equal. By default, the equals of an object is equivalent to the two objects. The valuetpye of the derived class of the object overwrites the equals method, which compares the logical equivalence of the two objects. That is to say, in C #, the default equals version of the reference type focuses on the reference equality, while the value type focuses on the logical equality. Of course, this does not always meet our requirements. So whenever we care more about the logical equivalence of the reference type, we should rewrite the equals method. The objects in the previous log that implement the icomparable <t> interface can be compared with each other, but the comparison results are 0, 1 and-1, which are not intuitive. In many cases, you may only need to know whether the two objects are equal, but do not need to know who the two objects are. In this case, you can override the equals method of the object class. Public override bool equal (Object OBJ) {If (this. compareto (OBJ) = 0) return true; else return false;} You can see that the equals method internally calls the compareto method to compare objects. Conclusion: There are two differences in C #: equal references and equal values. The two objects have the same value. For example, two integers with a value of 2 have equal values. Referencing equal means that the two objects to be compared are not two objects, but two "Object references". These two "Object references the same object. 1. For value type and value type, if the object value is equal, the equal operator (=) returns true; otherwise, false. 2. For reference types other than string, if two objects reference the same object, = returns true. For the string type, = compares the string value. = The operation compares whether the values of the two variables are equal. The equals () method compares whether the content of the two objects is consistent. Equals is used to compare whether the reference type is a reference to the same object. First, let's take a look Program : Using system; using system. collections. generic; using system. LINQ; using system. text; namespace csharpdemo {class person {private string name; Public string name {get {return name;} set {name = value ;}} public person (string name) {This. name = Name ;}} class program {static void main (string [] ARGs) {int I = 1; Int J = 1; console. writeline (I = J); // true console. writeline (I. equals (j )); // True 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); // true console. writeline (. equals (B); // true object G = A; object H = B; console. writeline (G = H); // false console. writeline (G. equals (h); // true person p1 = new person ("person"); person P2 = new person ("person"); console. writeline (p1 = P2); // false console. writeline (p1.equals (P2); // false person P3 = new person ("person"); person P4 = P3; console. writeline (P3 = P4); // true console. writeline (p3.equals (P4); // true console. readkey () ;}}equals method call output results are marked after the corresponding row. Why is this answer? Because the value type is stored in the memory stack (later referred to as the stack), the reference type variable is only the address of the reference type variable in the stack, and it is stored in the heap. = The operation compares whether the values of two variables are equal. For a referenced variable, it indicates whether the addresses of the two variables stored in the heap are the same, that is, whether the stack content is the same. The equals operation indicates whether the two variables are referenced to the same object, that is, whether the content in the heap is the same. String is a special reference type. in C #, many methods (including the equals () method) of the string object are overloaded ), make the string object use the same value type. Therefore, in the preceding example, the two comparisons of string a and string B are equal. For two different objects in the memory of object g and object H, the content in the stack is different, so they are not equal. G. Equals (h) uses the string equals () method, so it is equal (polymorphism ). If you modify string a and string B as follows: string a = "AA"; string B = "AA"; then, the comparison between G and H is equal. This is because the system does not allocate memory to string B, but points "AA" to B. Therefore, a and B point to the same string (the string is optimized by memory in this case ). P1 and P2 are two different objects in the memory, so the addresses in the memory must be different, so p1 = P2 will return false, because P1 and P2 are references to different objects, p1.equals (P2) returns false. For P3 and P4, P4 = P3, P3 assigns a reference to the object to P4. P3 and P4 are references to the same object, so true is returned for both comparisons. Ii. Operator Overloading PS: if an object is overloaded with the "=" operator, it must also be overloaded "! = "Operator, which is a basic principle. For operator overloading, see the next diary. To sum up the differences between referenceequals, equals, and =: referenceequals: static method, which cannot be rewritten and can only be referenced. If one parameter is null, false is returned and no exception is thrown, if the value type is compared, false is always returned. Equals: instance method. By default, you can compare, reference, or compare values. You can override this parameter. Objects can be compared by value. Static equals: static method, which cannot be rewritten. If equals is not overwritten, a reference is compared, or a value is compared. If the equals method is overloaded. Compare references, compare values, or compare by override equals. If one of the parameters is null, an exception = Operator is thrown: Compare by reference or compare by value. It can be rewritten. Is an operator. The final requirement is that if equals is overloaded, it is best to overload gethashcode, And the = operator must be overloaded. Iii. iequatable <t> in some cases, the interface may not need to determine the object size, but only need to give a conclusion of "whether two objects are equal. net also defines a public interface iequatable <t> {bool equals (t other );} for more information about this interface and the interfaces mentioned in previous diaries, see http://www.cnblogs.com/symphony2010/archive/2011/08/19/2145890.html 4. Summary of the previous examples, a general example is given to define a circle class using system; using system. collections. generic; using system. text; namespace objectcompare {/// <summary> /// center // </summa Ry> public struct circlecenter {public Double X; Public Double Y;} class circle: icomparable, icomparable <circle>, iequatable <circle> {public Double Radius = 0; // radius public circlecenter center; // center // the method defined by the icomparable interface public int compareto (Object OBJ) {If (! (Obj is circle) throw new argumentexception ("can only compare cirlce objects"); Return compareto (OBJ as circle );} // implement the icomparable <t> interface definition method public int compareto (circle other) {double ret = math. ABS (Other. radius-this. radius); If (Ret <1e-3) return 0; If (Other. radius <this. radius) return 1; Return-1;} // overwrite the gethashcode method of the object class public override int gethashcode () {// The integer part generates the same hash value return (INT) (radius * 1000);} // rewrite the equals method of the object class public override bool equals (Object OBJ) {If (this. compareto (OBJ) = 0) return true; return false;} // the method defined by the iequatable <circle> interface. Public bool equals (circle other) {return this. compareto (other) = 0;} // ---------------------------------------- // overload related operators // restart public static bool operator = (circle obj1, circle obj2) {return obj1. Equals (obj2);} public static bool Operator! = (Circle obj1, circle obj2) {return! (Obj1.equals (obj2);} public static bool operator> (circle obj1, circle obj2) {If (obj1.compareto (obj2)> 0) return true; return false ;} public static bool operator <(circle obj1, circle obj2) {If (obj1.compareto (obj2) <0) return true; return false;} public static bool operator <= (circle obj1, circle obj2) {If (obj1.compareto (obj2) <0) | (obj1.compareto (obj2) = 0) return true; return false ;} public static bool operator> = (circle obj1, circle obj2) {If (obj1.compareto (obj2)> 0) | (obj1.compareto (obj2) = 0) return true; return false ;}} Test Code Using system; using system. collections. generic; using system. text; namespace objectcompare {class program {static void main (string [] ARGs) {circle obj1 = new circle {radius = 100.1}; Circle obj2 = new circle {radius = 100.9 }; // test the overwriting method console. writeline (obj1.gethashcode (); // 100100 console. writeline (obj2.gethashcode (); // 100900 console. writeline (obj1.compareto (obj2); //-1 Console. writeline (Obj1.equals (obj2); // false // test the overloaded operator console. writeline (obj1 = obj2); // false console. writeline (obj1! = Obj2); // true console. writeline (obj1> = obj2); // false // The following test the circle object array sorting function: circle [] circles = new circle [10]; // create the circle object array random ran = new random (); For (INT I = 0; I <10; I ++) {circles [I] = new circle {radius = ran. next (1, 1000)/100.0};} console. writeline ("original array:"); array. foreach <circle> (circles, (circle) => {console. writeline ("round object hash code: {0}, radius: {1}", circle. gethashcode (), circle. radius) ;}); console. writeline ("\ n after sorting:"); array. sort (circles); array. foreach <circle> (circles, (circle) => {console. writeline ("round object hash code: {0}, radius: {1}", circle. gethashcode (), circle. radius) ;}); console. readkey () ;}} transferred from: http://www.cnblogs.com/eagle1986/archive/2012/02/03/2337315.html
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.