. NET Foundation Step-by-step screen [object-oriented new, this keyword]

Source: Internet
Author: User
Tags modifiers

Often people ask: young man, there is no object ah, I would like to help you to introduce a Ah, the young man will say: uncle, do not use my own new one is good. (PS: You have no object to deserve)

The top of course is a joke, programmers that will have no objects, their new one has AH. Okay, get into today's theme new and this keyword.

New keyword

New keywords can be used as operators, modifiers, or constraints in three ways:

1) New operator: Used to create objects and invoke constructors.

a) person person = new person ();//new is an operator
(1) Open up a suitable size space in memory
(2) Create objects in this space
(3) Call the constructor of this object
(4) Return the reference address of this space

Code Show:

Class Program {static void Main (string[] args) {Reporter rep = new Reporter ("journalist", 11, ' Male ', "            Candid "); Rep.            SayHello (); Rep.            Test ();        Console.readkey ();        }} public class Person {private string _name;            public string Name {get {return _name;}        set {_name = value;}        } private int _age;            public int Age {get {return _age;}        set {_age = value;}        } private char _gender;            Public Char Gender {get {return _gender;}        set {_gender = value;} The public person (string name, int. int, char gender) {this.            name = name; This.            Age = age; This.        Gender = Gender;        } public void Test () {Console.WriteLine ("Test");        } public void SayHello () {Console.WriteLine ("Hello, I am Human");    }public class Reporter:person {public Reporter (string name, Int. age, char Gender, string hobby) : Base (name, age, gender) {this.        Hobby = Hobby;        } private string _hobby;            public string Hobby {get {return _hobby;}        set {_hobby = value;} } public void Reportersayhello () {Console.WriteLine ("I call {0}, I am a dog, my hobby is {1}, I am {2} born, I am {3} years old this year", Thi S.name, this. Hobby, this. Gender, this.        Age);        } public new void SayHello () {Console.WriteLine ("Hello everyone, I am a journalist"); }    }

  

2) New modifier: When used as a modifier, the new keyword can explicitly hide members inherited from a base class.

Code Show:

public class BaseClass    {public        void Functiona ()        {            Console.WriteLine ("Basefunctiona/HTTP/ www.cnblogs.com/sosoft/");        }        public virtual void functionb ()        {            Console.WriteLine ("Basefunctionb http://www.cnblogs.com/sosoft/");        }    } Public   class Derivedclass:baseclass    {public        new void Functiona ()        {            Console.WriteLine ("Derivedfunctiona http://www.cnblogs.com/sosoft/" );        }        public override void Functionb ()        {            Console.WriteLine ("Derivedfunctionb http://www.cnblogs.com/sosoft/");        }    Call: BaseClass basefunction=new derivedclass (); Basefunction.functiona (); basefunction.functionb ();

Operation Result:

Basefunctiona Http://www.cnblogs.com/sosoft/DerivedFunctionB http://www.cnblogs.com/sosoft/

New is a hidden base class method, override is a base class method. If you want to access a base class member that is hidden by new, you need to use the Base keyword implementation.

The similarities and differences between hiding and overriding base class methods:

1: Method overrides: The method in the base class is identified with the virtual keyword, and then overridden in the inheriting class (override), so that the methods in the base class have been rewritten and have lost functionality . When a reference to an object of a base class is directed directly to an object that inherits the class (polymorphism), calling the method is the method that invokes the inherited class.

2: Method Hide: Regardless of whether a method in the base class uses the virtual keyword, the inheriting class can use the New keyword (without new, no error, but generate a compilation warning) to hide the methods in the base class, so-called hiding is hidden, not like rewriting, Rewriting is the original (in the base class) no longer exists, and the hidden is the original still exists . So when a reference to an object of a base class is directed directly to an object that inherits the class (polymorphism), calling the method is the method of the base class that is called.

3 ) New constraint: Used to constrain the type of a parameter that may be used as a type parameter in a generic declaration.

Code Show:

Class person<t> where T:new ()    {public        T GetName ()        {            return new T ();        }    }    Class Boy    {        private string _name;        public string Name        {            get{return _name;}            set {_name = value;}        }        Public Boy ()        {            _name = "Feng";        }    }    Class program    {        static void Main (string[] args)        {            person<boy> mboy = new Person<boy> () ;            Boy a = new boy ();            Console.WriteLine (a.name);            Console.WriteLine (Mboy.getname (). Name);            Console.readkey ();        }}

Operation Result:

Print out 2 "Feng"

4) new for polymorphic

A) For example, by using a base class extension to implement inherited polymorphism.

b) by inheriting the interface to achieve polymorphism.

Code Show:

Class Num {public static int i = 111;        public virtual void Showclassinfo () {Console.WriteLine ("I am the base class hehe");        The public virtual void Shownum () {Console.WriteLine ("The number of the base class is {0}", i.ToString ());        }} class Subnum:num {new public static int i = 222;        New as modifier: only hides the base class method public new virtual void Showclassinfo () {Console.WriteLine ("I am a sub-class haha"); }//override is a method that override the base class public override void Shownum () {Console.WriteLine ("The number of the subclass is {0}"        , i.ToString ());            }} class Program {static void Main (string[] args) {Num num1 = new Num ();//new operator usage Num1.            Shownum ();            Subnum sbnum = new Subnum (); The following 2 calls are methods of subclasses, but the implementation mechanism is not the same sbnum. Shownum ();//Result: 111 Sbnum. Showclassinfo ();//Result: I am a subclass of//new as a polymorphic usage: The following is a typical base class inheritance like polymorphic Num num2 = new Subnum ();//nuM2 is a base class variable, but pointing to a reference//call method of a Subnum instance will check the virtual method table at run time to determine the method num2 to invoke. Showclassinfo ();//Because the method is only hidden, there is no way to rewrite all or call the base class num2.        Shownum ();//method is overridden by all methods that call the subclass Console.readkey (); }    }

Note: High energy ahead:

The new keyword can be used in our program at all time, so where does the new keyword work?  Consider the following questions: 1. What is the difference between a new class object and a new struct or new enum?  A: New class, New completes 2 content: First, call the newobj command to allocate memory for the instance in the managed heap, and the other is to invoke the constructor to implement the object initialization. When new is a struct, the new operator is used to invoke its constructor to complete the initialization of the instance.
2, New in.  What can I do in addition to creating object instances in net?  A: You can create objects and call constructors as operators, as modifiers can be used to hide inherited members from base class members, implement virtual methods that hide base classes in derived classes, and cannot coexist with override; As a constraint, you can constrain a parameter type that may be used as a type parameter in a generic declaration, that is, the new constraint specifies that any type parameter in a generic class declaration must have a public parameterless constructor, and that the new keyword is used for polymorphism.
3. Can the new operator be overloaded? Answer: The new operator cannot be overloaded.
4. What is the role of the new keyword in generics? A: The new operator returns a reference to the memory address of the managed heap allocated by the system, and new allocates memory failure, which throws a OutOfMemoryException exception.
5. What is the difference between an inherited method and an override? Answer: New is a hidden base class method, override is a base class method. If you want to access a base class member that is hidden by new, you need to use the Base keyword implementation.
What is the difference between 6, int i and int i = new int ()? A: When new int, the new operator initializes its value to 0, allowing the constructor to perform a more advantageous initialization operation.

 

this keyword

1), object representing the current class

Code Show:

Class MyClass    {        //declares an integer field named "Myval" public       int myval = ten;        Declares a constructor that takes a parameter named "Myval" public        MyClass (int myval)        {            //' This ' represents the current instance of the MyClass class            // Here through this can be semantically distinguished member name myval and parameter name myval            this.myval + = Myval;            Use this as the argument for the current object to pass to the Compute method            int res = myval + myclass1.compute (this);}    }

  

2), the constructor for calling this class, shown in the class: this

Code Show:

Class MyClass    {        //declares an integer field named "Myval" public       int myval = ten;        Declares a constructor that takes a parameter named "Myval" public        MyClass (int myval)        {            //' This ' represents the current instance of the MyClass class            // Here through this can be semantically distinguished member name myval and parameter name myval            this.myval + = Myval;        }    }

  

3), declare indexer. (PS: This will be updated later in the blog)

Code Show:

<summary>  ///////</summary> public NameValueCollection Attr = new NameValueCollection ();  <summary>///*************************////* This Usage 3: Declaration indexer *////////</summ ary>//<param name= "key" ></param>///<returns></returns> public string this[string key] { C3/>set     {         Attr[key] = value;     }      Get     {         return attr[key];}     }

4), How to extend the object

Code Show:

<summary>///person//</summary>public class person{//<summary>///gender///        </summary> public        string Sex {set; get;}}  <summary>///Auxiliary class///</summary>public Static class helper{//<summary>//    /*********** /////    * This usage 4: How to extend the object *//////*****************************///    </summary> //    <param name= "item" ></param>///    <returns></returns> public    static String Getsex (this person item)    {        return item. Sex;}    } Call: Person person = new person ();p Erson. Getsex ();

  

This article is here, and finally make a small ad: QQ Group: . NET step by Step screen number:590170361 (Dabigatran Note: Blog Park to see)

. NET Foundation Step-by-step screen [object-oriented new, this keyword]

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.