C # Basic Knowledge: Basic knowledge (12) Super-Class Object

Source: Internet
Author: User

Object-oriented features: encapsulation, inheritance, and polymorphism. Where do classes inherit from? In object-oriented languages, there are base classes or superclasses, that is, all classes are inherited from this class. This superclass is called object .. Net describes the object class as follows:
Supports all classes in the. NET Framework class hierarchy and provides low-level services for derived classes. This is the final base class of all classes in. NET Framework; it is the root of the type hierarchy.
As a superclass, objects define some key methods. As follows:

Equals Method -- used to compare whether two instances are equal.
Public Virtual bool equals (Object OBJ), compare whether the current instance is equal to OBJ;
Public static bool equals (Object obja, object objb), and compares the two instances.

Finalize method -- allows the object to try to release resources and perform other cleanup operations before "Garbage Collection" recycles the object.

Gethashcode Method -- obtains the hash value of an object.

GetType Method -- get the type of the current instance.

The memberwiseclone method creates a superficial copy of the current instance. If the current instance has a value, only the value of the value type is obtained in the newly created instance, and the reference type is not obtained.

Referenceequals Method -- compare whether two instances are the same and use the same method as static bool equals (Object obja, object objb.

Tostring method-this usually uses a lot of strings to return the string of the current instance.
Objects are superclasses, so all classes in C # Have these methods.

The following describes the equals and tostring methods.
1. Object comparison
C # contains the value type and reference type. A simple understanding is that the value type stores the value of the object, and the reference type is the instance reference, similar to the C language pointer. Therefore, when using object comparison, the value type compares whether the values of two objects are equal, and the reference type compares whether the specified reference references the same object. Of course, sometimes the instance values that the reference type points to are the same.
The following code compares objects:

Using system; using system. collections. generic; using system. text; namespace yys. csharpstudy. mainconsole. aboutobject {public class int32value: icloneable {// field. It is best to assign the initial value private int intvalue = 0 to the defined field; /// <summary> /// attribute /// </Summary> Public int intvalue {get {return this. intvalue;} set {This. intvalue = value ;}/// <summary> // defines a non-parameter constructor /// </Summary> Public int32value () {}/// <summary> /// constructor with parameters /// </Summary> Public int32value (INT value) {This. intvalue = value;} // <summary> //// implement the icloneable interface // </Summary> Public object clone () {return this. memberwiseclone ();}}}

Call:

Using system; using yys. csharpstudy. mainconsole. aboutobject; namespace yys. csharpstudy. mainconsole {class program {static void main (string [] ARGs) {// declare a reference value1 of the int32value type, pointing to an instance int32value value1 = new int32value (30 ); // declare value2 and point to value1. At this time, the two references point to the int32value value2 = value1 of an instance; // use = to compare the console. writeline (string. format ("value1 and value2 {0}", value1 = value2? "Same": "different"); // same // call clone, copy a copy of value1 and assign it to value2 // at this time, the two instances have value2 = (int32value) value1.clone (); // use = to compare the console. writeline (string. format ("value1 and value2 {0}", value1 = value2? "Same": "different"); // not the same // assign value1 to value2, then they direct to the same instance value2 = value1; // use equals to compare the console. writeline (string. format ("value1 and value2 {0}", value1.equals (value2 )? "Same": "different"); // same // call clone, copy a copy of value1 and assign it to value2 // at this time, the two instances have value2 = (int32value) value1.clone (); // compare console with equals. writeline (string. format ("value1 and value2 {0}", value1.equals (value2 )? "Same": "different"); // different console. Readline ();}}}

Result:

The Code shows that:

A. For the reference type, the = Operator transfers the reference from one variable to another, so the = variable references the same object;
 
B. Use the = Operator to return true for referencing two identical variables;

C. The object clone method generates a new instance and returns a reference to the instance. All the Field Values of the instance are the same as those of the original object, that is, the clone method gets a copy of the object. The protection method inherited from the object class memberwiseclone returns a copy of the current object;

D. the reference of the object returned by the clone method is different from that of the original object. The = Operator returns false;

E. The equals method inherited from the object has the same result as the = Operator. It only compares whether the current reference (this) and the reference saved by the parameter are referenced in the same object.
Based on the above Code, rewrite the equals method.

Using system; using system. collections. generic; using system. text; namespace yys. csharpstudy. mainconsole. aboutobject {public class int32value: icloneable {// field. It is best to assign the initial value private int intvalue = 0 to the defined field; /// <summary> /// attribute /// </Summary> Public int intvalue {get {return this. intvalue;} set {This. intvalue = value ;}/// <summary> // defines a non-parameter constructor /// </Summary> Public int32value () {}/// <summary> /// The constructor with parameters /// </Summary> Public int32value (INT value) {This. intvalue = value;} // <summary> //// implement the icloneable interface // </Summary> Public object clone () {return this. memberwiseclone ();} /// <summary> /// override the equals method /// </Summary> /// <Param name = "OBJ"> </param> /// <returns> </returns> Public override bool equals (Object OBJ) {bool isequals = object. referenceequals (OBJ, this); If (isequals = f ALSE) {int32value value = OBJ as int32value; If (value! = NULL) {isequals = value. intvalue = This. intvalue ;}} return isequals ;}}}

Call

Using system; using yys. csharpstudy. mainconsole. aboutobject; namespace yys. csharpstudy. mainconsole {class program {static void main (string [] ARGs) {// declare a reference value1 of the int32value type, pointing to an instance int32value value1 = new int32value (30 ); // declare value2 and point to value1. At this time, the two references point to the int32value value2 = value1 of an instance; // use = to compare the console. writeline (string. format ("value1 and value2 {0}", value1 = value2? "Same": "different"); // same // call clone, copy a copy of value1 and assign it to value2 // at this time, the two instances have value2 = (int32value) value1.clone (); // use = to compare the console. writeline (string. format ("value1 and value2 {0}", value1 = value2? "Same": "different"); // not the same // assign value1 to value2, then they direct to the same instance value2 = value1; // use equals to compare the console. writeline (string. format ("value1 and value2 {0}", value1.equals (value2 )? "Same": "different"); // same // call clone, copy a copy of value1 and assign it to value2 // at this time, the two instances have value2 = (int32value) value1.clone (); // compare console with equals. writeline (string. format ("value1 and value2 {0}", value1.equals (value2 )? "Same": "different"); // same console. Readline ();}}}

Result:

Modified code:
If the equals method is overwritten, the program running result is different: equals does not compare whether the object references saved by the two variables are the same, but compares whether the objects referenced by the two variables have the same attribute values.
The overwrite equals execution process is as follows:
Let's take a look at the specific execution process of the covered equals method:

A. Use the object static method referenceequals to compare whether the OBJ parameter and the current object reference (this) are the same. If the reference is the same, the object must be the same;
B. If the variable obj is different from the current reference, use the as operator to convert the OBJ type to the same type as the current object, if the conversion succeeds, the OBJ variable references the same object as the current object class. After the as operator is converted, the object is referenced. Otherwise, null is returned. Only objects of the same type need to be compared, different types of objects must be different objects;
C. If the as operator is successfully converted to an object, compare whether the Field Values of the object referenced by the current object reference (this) and the OBJ parameter are equal.
The above two sections of Code show that:
= The equals method of the object class compares whether the object references the same, and does not compare whether the object's fields are equal. The equals method can overwrite, in order to allow them to perform equivalent comparison or other comparisons on the object fields.
Therefore, if you need to compare two C # reference type variables, you can use the = operator unless you are sure that you want to compare them with object references. Otherwise, you should use the equals method of the object, prevent the class to which the object belongs from overwriting this method.

The above is a comparison of the reference type, relatively speaking, the comparison of the value type is pure. The value type does not exist, so the value type is to compare whether the values of two objects are equal. Of course, if the equals method is overwritten, it will be excluded. However, in general, we do not need to overwrite the equals method. For the reference type, the equivalent comparison is to compare the reference of the object, and the two objects that reference different should be different objects; For the value type, the comparison is the value of all fields, two objects with different field values are different objects. The equals method must be overwritten only in special cases. A special object comparison method of a class has been defined.
Note the following when overwriting the equals method:
Note: In theory, any code can overwrite the equals method, but the following principles must be ensured:
A. Equals can only be used for object comparison and cannot be used for any other purposes;
B. For two existing objects without any changes to the object, the returned results should be the same no matter when the equals method is called;
C. For objects a and B, the results returned by A. Sort se (B) and B. Equals (a) should be the same;
D. overwrite the equals method, and overwrite the gethashcode (method.

Ii. tostring ()
Code:

Public class int32value: icloneable {// field. It is best to assign the initial value private int intvalue = 0 to the defined field; /// <summary> /// attribute /// </Summary> Public int intvalue {get {return this. intvalue;} set {This. intvalue = value ;}/// <summary> // defines a non-parameter constructor /// </Summary> Public int32value () {}/// <summary> /// constructor with parameters /// </Summary> Public int32value (INT value) {This. intvalue = value;} // <summary> //// implement the icloneable interface // </Summary> Public object clone () {return this. memberwiseclone ();} // <summary> // rewrite the tostring method /// </Summary> /// <returns> </returns> Public override string tostring () {return this. intvalue. tostring (); // return "rewrite tostring ";}}

Call:

Class program {static void main (string [] ARGs) {int32value value = new int32value (30); console. writeline (value. tostring (); // 30 // console. writeline (value. tostring (); // rewrite tostring console. readline ();}}

It can be seen that the tostring method can be overwritten with any code, as long as the string is returned, but the returned value must also meet the requirements when overwriting.

Code download: http://download.csdn.net/detail/yysyangyangyangshan/4463710

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.