Basic knowledge of C #: Basics (12) Super Class object

Source: Internet
Author: User
Object-oriented three major features: encapsulation, inheritance, polymorphism. So where does the class inherit from? In object-oriented languages, there is a concept of a base class or a superclass, that is, all classes inherit from this class, and this superclass is called object. NET, which describes the object class:
Supports all classes in the. NET Framework class hierarchy and provides low-level services for derived classes. This is the final base class for all classes in the. NET Framework, which is the root of the type hierarchy.
Since it is a superclass, object defines a number of key methods. As follows:

The Equals method--used to compare whether two instances are equal.
Public virtual bool Equals (Object obj) to compare whether the current instance is equal to obj;
public static bool Equals (Object obja,object objb), which compares the specified two instances for equality.

Finalize Method--allows object to attempt to free resources and perform other cleanup operations before garbage collection reclaims the object.

GetHashCode Method--Gets the hash value of an object.

GetType method-Gets the type of the current instance.

MemberwiseClone Method-Creates a shallow copy of the current instance, that is, 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 does not get the value.

ReferenceEquals Method--Compares whether two instances are the same as the static bool Equals (Object obja,object objb) usage.

ToString Method-This is usually used more than the string used to return the current instance.
Object is a superclass, so all classes in C # have these methods.

The following equals and ToString methods are highlighted below.
I. Comparison of objects
C # has value types and reference types, and a simple understanding is that value types hold the value of an object, whereas a reference type is a reference to an instance, similar to a C-language pointer. Therefore, when using object comparisons, value types compare two object values for equality, and reference types compare whether the specified reference refers to the same object. Of course, it is also sometimes compared to whether the instance values pointed to by the reference type are the same.
The following is the code for object comparisons:

Using system;using system.collections.generic;using system.text;namespace yys. csharpstudy.mainconsole.aboutobject{public    class int32value:icloneable    {        //field, defining the field is best to assign the initial value        private int intvalue = 0;        <summary>//Properties///        </summary> public        int intvalue        {            get            {                return This.intvalue;            }            Set            {                this.intvalue = value;            }        }        <summary>        ///define a parameterless constructor        ///</summary> public Int32value () {}///        <summary >        ///constructor with parameters        ///</summary> public int32value (int value)        {            this.intvalue = value;        }        <summary>        /////Implement 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) {//declares a int32value            A reference to the type value1, pointing to an instance int32value value1 = new Int32value (30);            Declare value2, point to Value1, at which point two references are int32value value2 = value1 that point to an instance; Use = = to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1 = = value2? "Same": "Not the same"));//Call clone, copy a copy of value1, assign to value2//This is two instances value2 = (Int32value) val Ue1.            Clone (); Use = = to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1 = = value2?            "Same": "Not the same");//different//assigns value1 to value2, at this point they point to the same instance value2 = value1; Use Equals to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1. Equals (value2)? "Same": "Not the same"));//Call clone, copy a copy of value1, assign to value2//This is two instances value2 =(Int32value) value1.            Clone (); Use Equals to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1. Equals (value2)?        "Same": "Not the same");//Not identical console.readline (); }    }}

Results:

As you can see from the code:

A, for reference types, the = operator passes a reference from one variable to another, so = the variable on either side refers to the same object;

b, for referencing the same two variables, use the = = operator to return true;

C, the object's clone method produces a new instance that returns a reference to the instance where all field values are the same as 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, for the object returned by the Clone method, whose reference differs from the original object, the = = operator returns false;

The result of the Equals method inherited from object is the same as the = = operator, except that the reference to the current reference (this) and the argument saved are referenced to the same object.
On the basis of the above code, override 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 an initial value of private in        T intvalue = 0;            <summary>//Properties///</summary> public int Intvalue {get            {return this.intvalue;            } set {this.intvalue = value;        }}///<summary>///define a parameterless constructor///</summary> public Int32value () {}            <summary>///constructor with parameters///</summary> public int32value (int value) {        This.intvalue = value;        }/////<summary>/////implement ICloneable interface/////</summary> public Object Clone () {return this.        MemberwiseClone (); }///<summary>//Cover Equals method///</summary>//<param name= "obj" ></param>///<returns></returns> public Overri            de bool Equals (object obj) {bool isequals = object.referenceequals (obj, this);                if (isequals = = False) {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) {//declares a int32value            A reference to the type value1, pointing to an instance int32value value1 = new Int32value (30);            Declare value2, point to Value1, at which point two references are int32value value2 = value1 that point to an instance; Use = = to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1 = = value2? "Same": "Not the same"));//Call clone, copy a copy of value1, assign to value2//This is two instances value2 = (Int32value) val Ue1.            Clone (); Use = = to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1 = = value2?            "Same": "Not the same");//different//assigns value1 to value2, at this point they point to the same instance value2 = value1; Use Equals to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1. Equals (value2)? "Same": "Not the same"));//Call clone, copy a copy of value1, assign to value2//This is two instances value2 =(Int32value) value1.            Clone (); Use Equals to compare Console.WriteLine (string. Format ("value1 and value2 {0}", value1. Equals (value2)?        "Same": "Not the same"));//Same console.readline (); }    }}

Results:

The Modified code:
Overridden by the Equals method, the program runs differently: equals no longer compares two variables to the same object reference, but rather compares the objects referenced by the two variables with the same property values.
After the overridden equals execution process is this:
Let's take a look at the specific execution flow of the after-overwrite equals method:

A, use the object static method referenceequals The comparison parameter obj and the current object reference (this) is the same, if the reference is the same, it must be the same object;
b, if the variable obj and the current reference are not the same, use the as operator, try to convert the obj type to the same type as the current object, and the conversion succeeds in representing that the obj variable refers to the same object as the current object class, the as operator references the object after the conversion, otherwise null, only objects of the same type need to be compared , different types of objects are necessarily different objects;
C, if the as operator succeeds in converting the object, further compares the current object reference (this) and the parameter obj to refer to the object's field values for equality.
The above two pieces of code can be seen:
The Equals method of the = = and object classes are the same as the reference to the object, and do not compare the object's fields for equality, whereas the Equals method can be overridden in order to allow it to compare or otherwise compare the fields of an object.
Therefore, if you need to compare two C # Reference type variables, you should use the Equals method of the object to prevent the class to which the object belongs, unless you are sure that you want to compare the object reference with the = = operator.

The above is a comparison of reference types, relative to which the comparison of value types is purely. A value type is not a reference, so a value type is a comparison of two object values for equality. Unless, of course, the Equals method is overridden. However, in general, we do not need to overwrite the Equals method. For reference types, an equivalent comparison is a reference to a comparison object, and a reference to a different two object should be a different object; For a value type, the value of all fields is compared, and two objects with different field values are different objects. Only in special cases do you need to override the Equals method, and you have defined a special object comparison method for a class.
For overriding the Equals method, be aware that:
Note: It is theoretically possible to override the Equals method with arbitrary code, but ensure the following principles:
A, equals can only be used for object comparison, can not do any other purposes;
b, for two existing objects, if the object has not changed any time, call the Equals method, the result of the return should be the same;
C, for objects A and B, then A. Equalse (b) and B. Equals (a) The result of the return should be the same;
D, covering the Equals method, but also to overwrite the GetHashCode (method), which is explained in detail later.

Two, ToString ()
Code:

   public class Int32value:icloneable {//field, the Definition field is best assigned the initial value private int intvalue = 0;            <summary>//Properties///</summary> public int Intvalue {get            {return this.intvalue;            } set {this.intvalue = value;        }}///<summary>///define a parameterless constructor///</summary> public Int32value () {}            <summary>///constructor with parameters///</summary> public int32value (int value) {        This.intvalue = value;        }/////<summary>/////implement ICloneable interface/////</summary> public Object Clone () {return this.        MemberwiseClone (); }///<summary>//Rewrite ToString Method///</summary>//<returns></retur       Ns> public override string ToString () {     return this.intValue.ToString ();        Return "rewrite ToString"; }    }

Call:

     Class program    {        static void Main (string[] args)        {            Int32value value = new Int32value (+);            Console.WriteLine (value. ToString ());//30            //console.writeline (value. ToString ());//rewrite ToString            console.readline ();        }    }

As you can see, the ToString method can be overwritten with any code, as long as a string is returned, but the return value that meets the requirements is returned when overwriting.

The above is the basic knowledge of C #: Basic knowledge (12) Super Class object content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.