. NET basics step by step: [object-oriented new, this keyword],. net keyword

Source: Internet
Author: User

. NET basics step by step: [object-oriented new, this keyword],. net keyword

Some people may often ask: Are there any objects? Do you want me to introduce one? The young man will say, "Uncle, I don't need to create one myself. (PS: You deserve no objects)

The above is of course a paragraph. Programmers will have no object, and they will have a new one. Now, enter the keywords of today's topic new and this.

New Keyword

New The keyword can be used as an operator, modifier, or constraint:

1)New Operator: used to create objects and call constructors.

A)Person person = new Person (); // new is an operator.
(1) Open up a suitable size space in the memory
(2) create an object in this space
(3) Call the constructor of this object
(4) return the reference address of the space.

Code display:

Class Program {static void Main (string [] args) {Reporter rep = new Reporter ("Reporter", 11, 'male', ""); 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 ;}} public Person (string name, int age, char gender) {this. name = name; this. age = age; this. gender = gender;} public void Test () {Console. writeLine ("test");} public void SayHello () {Console. writeLine ("Hello everyone, I am a human") ;}} public class Reporter: Person {public Reporter (string name, int age, char gender, string Hober): base (name, age, gender) {this. holobby = holobby;} private string _ holobby; public string holobby {get {return _ holobby;} set {_ holobby = value ;}} public void ReporterSayHello () {Console. writeLine ("My name is {0}. I am a paparazzi. My hobby is {1}. I am a {2} student. I am {3} years old.", this. name, this. holobby, this. gender, this. age);} public new void SayHello () {Console. writeLine ("Hello everyone, I am a reporter ");}}

  

2)New Modifier: when used as modifier, new Keywords can explicitly hide members inherited from the base class.

Code display:

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 ();

Running result:

 BaseFunctionA http://www.cnblogs.com/sosoft/ DerivedFunctionB http://www.cnblogs.com/sosoft/

The new method hides the base class method, and the override method overwrites the base class method. To access new hidden base class members, use the base keyword.

Similarities and differences between hiding and rewriting basic class methods:

1: Method Rewriting: the method in the base class is identified by the virtual keyword, And Then override the class in the inheritance class.The methods in the base class have been rewritten and the functions have been lost.. When the reference of the base class object is directed to the object of the inherited class (polymorphism), this method is called to inherit the class method.

2: Method hiding: no matter whether the method in the base class uses the virtual keyword or not, the new Keyword can be used in the inherited class. (if the new keyword is not used, no errors will be generated, but a compilation warning will be generated) hide the methods in the base class. Hiding means hiding. Unlike rewriting,Rewriting means that the original (in the base class) does not exist, while hiding is the original. Therefore, when the reference of a base class object is directed to an object that inherits the class (polymorphism), calling this method is the method of the base class called.

 

3)New Constraint: used to restrict the types of parameters that may be used as type parameters in a generic declaration. 

Code display:

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();        }}

Running result:

Print two "feng"

4)NewImplementation of Polymorphism

A) For example, inheritance polymorphism can be achieved through base class extension.

B) realize polymorphism through the inheritance interface.

Code display:

Class Num {public static int I = 111; public virtual void ShowClassInfo () {Console. writeLine ("I Am a base class heh");} public virtual void ShowNum () {Console. writeLine ("the base class number is {0}", I. toString () ;}} class SubNum: Num {new public static int I = 222; // new as modifier: only hide the method with the same name as the base class public new virtual void ShowClassInfo () {Console. writeLine ("I Am a subclass haha");} // override overwrites the base class method public override void ShowNum () {Console. writeLine ("The subclass number is {0}", I. toString () ;}} class Program {static void Main (string [] args) {Num num1 = new Num (); // usage of the new operator num1.ShowNum (); subNum sbnum = new SubNum (); // The following two calls are subclass methods, but the implementation mechanism is not the same as sbnum. showNum (); // result: 111 sbnum. showClassInfo (); // result: I am a subclass. // new is used as a polymorphism. The following is a typical base class that inherits polymorphism-like Num num2 = new SubNum (); // although num2 is a base class variable, it directs to a SubNum instance like this. // when calling a method, it checks the virtual method table at runtime, to determine the method num2.ShowClassInfo () to be called; // The method num2.ShowNum () of the base class to be called is not overwritten because the method is only hidden (); // The method is overwritten by all the methods that call the subclass Console. readKey ();}}

Note: High Energy ahead:

In our program, the new keyword is used without any time. Where can the new Keyword be used? Consider the following questions: 1. What is the difference between a new class object and a new struct or an enum? A: When a new class is created, new completes two tasks: one is to call the newobj command to allocate memory to the instance in the managed heap, and the other is to call the constructor to initialize the object. When a new struct is used, the new operator is used to call its constructor to complete instance initialization.
2. What can new do in addition to object creation in. NET? A: The new Keyword: you can create an object and call constructor as an operator. As a modifier, you can hide an inherited member from a base class member to hide the virtual method of the base class in a derived class, cannot coexist with override. as a constraint, you can use 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 the generic class declaration must have a common no-argument constructor. The new keyword is used to implement polymorphism.
3. Can the new operator be reloaded? A: The new operator cannot be overloaded.
4. What is the role of the new keyword in generics? A: The new operator is used to return a reference pointing to the memory address of the managed heap allocated by the system. If the memory allocated by the new operator fails, an OutOfMemoryException is thrown.
5. What is the difference between a new inherited method and override? A: The new method hides the base class method, and the override method overwrites the base class method. To access new hidden base class members, use the base keyword.
6. What are the differences between int I and int I = new int? A: When a new int is used, the new operator is used to initialize the value 0, so that the constructor can perform better initialization operations.

 

This keyword

1) represents the object of the current class

Code display:

Class MyClass {// declare an integer field named "myVal" public int myVal = 10; // declare a constructor, this function carries a public MyClass (int myVal) parameter named "myVal) {// "this" indicates the current instance of the MyClass class. // here, this can be used to distinguish the member name myVal from the parameter name myVal this. myVal + = myVal; // use this as the real parameter of the current object and pass it to the Compute method int res = myVal + MyClass1.Compute (this );}}

  

2) Call the constructor of the class displayed in the class: this

Code display:

Class MyClass {// declare an integer field named "myVal" public int myVal = 10; // declare a constructor, this function carries a public MyClass (int myVal) parameter named "myVal) {// "this" indicates the current instance of the MyClass class. // here, this can be used to distinguish the member name myVal from the parameter name myVal this. myVal + = myVal ;}}

  

3) Declare the indexer. (PS: This will be updated in subsequent blogs)

Code display:

/// <Summary> ///// </summary> public NameValueCollection Attr = new NameValueCollection (); /// <summary> ////*************************///// * this usage 3: declare the indexer * // ****************************** // </ summary> /// <param name = "key"> </param> // <returns> </returns> public string this [string key] {set {Attr [key] = value ;} get {return Attr [key] ;}}

4 ),Extension object Method

Code display:

/// <Summary> /// abstract description of 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: extension object Method */////*****************************/ /// </summary> /// <param name = "item"> </param> /// <returns> </returns> public static string GetSex (this Person item) {return item. sex ;}} call: Person person = new Person (); person. getSex ();

  

This article is here, and finally a small advertisement: QQ group: . NET Step by stepGroup Number:590170361 (Add group remarks: what you see in the blog Park)

 

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.