What are the similarities and differences between the three comparison methods defined in system. object?

Source: Internet
Author: User

Analyze problems

In the previous sections of this book, I have introduced all methods in system. object. Three methods are designed to compare objects. They are:

(1) Static bool referenceequals (Object A, object B ).

(2) Static bool equals (Object A, object B ).

(3) virtual bool equals (Object OBJ ).

1. Static Method: referenceequals compares data types. It can be seen from the parameter type that it can be used not only to compare two reference type objects, but also to compare two value type objects. Of course, according to the characteristics of the value type and reference type, the referenceequals method makes sense only when applied to the reference type. If you compare two value types, false is always returned, whether they are equal or not. When the current code is executed:

  

int i=0;Console.WriteLine(object.ReferenceEquals(i,i));

The result is still false. Readers can try to think about the cause from the principle of packing and unpacking.

2. Static Method: equals is another static comparison method. Its functions vary according to different types. In fact, the function of the equals method depends on the implementation of the Instance equals method. In general, the content of the static equals method is divided into two steps: first, check whether the two objects are constant (= ), call the instance equals method of one of the parameter objects to determine whether the two objects are consistent.

Note:

For value type and reference type, the concept of checking whether two objects are constant (=) is different. For the reference type, this check indicates whether the reference is equal, and for the value type, the check is a pointer to the content.

Using the transmitter, you can clearly see the code of the static method equals:

public static bool Equals(object objA,object objB){  return ((objA==objB)||(((objA!=null)&&(objB!=null))&&(objA.Equals(objB)));}

As previously analyzed, the equals method first uses the = Operator to check whether the parameter objects are equal, then checks the null references, and calls the instance method equals for comparison. This implementation relies entirely on the implementation of the instance method equals, so the reader will not need to hide the static equals method, but should directly focus on the instance method equals.

3. instance method: equals actually undertakes most of the comparative work. It is a virtual instance method. When users need to build custom comparisons, they need to write the equals method. The following is the intermediate code of mscorlib. dll. It shows the default implementation of the equals method in the object:

  

It looks very simple. The internalequals method is called to check whether the memory addresses of the two objects are equal. That is to say, the default Implementation of equals is to reference equal comparisons. As I have already introduced in the previous chapter, the reference is not practical in some cases, and the content may be more in line with the business logic requirements. At this time, the programmer needs to write the instance equals Method for his own type. In fact, valuetype, a base class of all value types, has overwritten the instance equals method. The following code is an example of rewriting.

  

Using system; namespace testoverrideequals {class overrideequals {static void main () {myobject O1 = new myobject (10, "I am a string"); myobject O2 = new myobject (10, "I am a string"); // print the reference comparison result console. writeline ("reference comparison: {0}", object. referenceequals (O1, O2 ). tostring (); // print the content comparison result console. writeline ("Custom content comparison: {0}", o1.equals (O2 ). tostring (); console. read () ;}} class myobject {private int _ Myint; private string _ My String; Public myobject () {} public myobject (int I, string s) {_ Myint = I; _ mystring = s;} public override bool equals (Object OBJ) {// check if (OBJ = NULL) {return false;} // compare the null references. If (object. referenceequals (this, OBJ) {return true;} // check whether the two types are equal // considering the impact of inheritance, the runtime type may not be myobject // so use reflection to get the exact type and sacrifice performance to ensure correctness if (this. getType ()! = Obj. getType () {return false;} // compare the implementation content with myobject right = OBJ as myobject; If (_ Myint = right. _ Myint & // although the string type is a reference type, the ==_mystring = right is implemented for content comparison. _ mystring) {return true;} return false ;}}}

In the above Code, myobject overwrites the system. object instance equals method to achieve content comparison. The execution program can get the following result:

  

Note:

The compilation of the above Code generates a warning because myobject has written the equals method but has not rewritten the gethashcode method, which may cause potential risks, this will be covered in subsequent chapters.

Answer

The static referenceequals method implements reference comparison. The static equals method allows you to call the instance equals method more efficiently. The instance equals method is a virtual method. The default implementation is the reference type. You can override the instance equals method as needed. The value type's base class valuetype overrides the equals method to achieve content comparison.

 

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.