The difference between c#base and this

Source: Internet
Author: User



Turn from (https://www.cnblogs.com/reommmm/archive/2009/03/23/1419573.html)






The New keyword has aroused a lot of attention, especially thanks to Anders Liu's supplement, let me feel that the communication platform given by the blog Park is really ubiquitous. So, we need to continue this topic, to carry out the key words that I think are most worthy of attention, this article is focused on the Access keyword (Access Keywords): base and this. Although access to the keyword is not difficult to understand the topic, we still have a place to discuss in depth to clarify the idea. Still the old way, my question is listed first, whether you are ready.



? Is it possible to use base and this in static methods, why?



? What are the common uses of base? What are the this often used in?



? Can base access all members of the base class?



? If there are three or more inheritance, then the base of the most subordinate derived class points to that layer? For example. NET system, if base access, should be the direct parent class instance, or the highest level class instance?



? When base and this are applied to constructors, what is the order of execution of the inherited class object instantiation?



2. Basic Concepts



Base and this are attributed to the Access keyword in C #, which, as the name implies, is used to implement the inheritance mechanism of access operations to satisfy the access to the object members, thus providing a more flexible way to handle the polymorphic mechanism.



2.1 Base keyword



It is used to implement access to a base class public or protected member in a derived class, but only in constructors, instance methods, and instance property accessors, and the specific features of the summary in MSDN include:



? Calls a method on the base class that has been overridden by another method.



? Specifies the base class constructor that should be called when creating an instance of a derived class.



2.2 This keyword



It is used to refer to the current instance of the class, and also to include inherited methods, which can often be hidden this,msdn the summary functionality in the main includes:



? Qualify a member that is hidden by a similar name



? To pass an object as a parameter to another method



? Declaring indexers



3. In Layman's



3.1 example is the upper



The following is a small example to synthesize the description of the application of base and this in the access operation, thus having an overview of it, more detailed rules and further elaboration. This example does not have a complete design concept and is mainly used to illustrate the use and difficulty of the base and this keyword, as follows:


using System;

namespace Anytao.net.My_Must_net

{

public class Action

{

public static void ToRun (Vehicle vehicle)

{

Console.WriteLine ("{0} is running.", Vehicle.ToString ());

}

}

public class Vehicle

{

private string name;

private int speed;

private string [] array = new string [10];



public Vehicle ()

{

}

// Limit members hidden by similar names

        public Vehicle (string name, int speed)

{

this.name = name;

this.speed = speed;

}

public virtual void ShowResult ()

{

Console.WriteLine ("The top speed of {0} is {1}.", Name, speed);

}

public void Run ()

{

// Pass the current instance parameters

            Action.ToRun (this);

}

// Declare the indexer, which must be this, so that you can index objects like array

        public string this [int param]

{

get {return array [param];}

set {array [param] = value;}

}

}

public class Car: Vehicle

{

// The derived class communicates with the base class, implemented as base, the base class is called first

// Specify the base class constructor that should be called when creating a derived class instance

        public Car ()

: base ("Car", 200)

{}



public Car (string name, int speed)

: this ()

{}



public override void ShowResult ()

{

// Call methods on the base class that have been overridden by other methods

            base.ShowResult ();

Console.WriteLine ("It ‘s a car ’s result.");

}

}

public class Audi: Car

{

public Audi ()

: base ("Audi", 300)

{}



public Audi (string name, int speed)

: this ()

{

}

public override void ShowResult ()

{

// It can be seen from three-level inheritance that base can only inherit its direct base class members

            base.ShowResult ();

base.Run ();

Console.WriteLine ("It ‘s audi ‘s result.");

}

}

public class BaseThisTester

{

public static void Main (string [] args)

{

Audi audi = new Audi ();

audi [1] = "A6";

audi [2] = "A8";

Console.WriteLine (audi [1]);

audi.Run ();

audi.ShowResult ();

}

}

} 
base and this example


3.2 Example Description



The above example basically includes all the basic function demos that are used by base and this, and the instructions can be explained in the comments, and the following description is a further elaboration and supplement to the annotations to illustrate several key points in the application:



? Base is commonly used to communicate with the base class when the derived class object is initialized.



? Base can access the public and protected members of the base class, and private members are inaccessible.



? This refers to the class object itself, which accesses all constants, fields, properties, and method members of this class, regardless of the access level of the access element. Because this is only confined to the inside of the object, the outside of the object is not visible, this is the basic idea of this. In addition, a static member is not part of an object and therefore cannot be referenced in a static method.



? In multi-tier inheritance, there are two ways that a base can point to a parent class: First, if there is an overload, base will point to a method that inherits directly from the parent class member, such as the Showresult method in the Audi class, which is accessed using base car.showresult () method instead of accessing the Vehicle.showresult () method, but without overloading, base can point to either the public or protected methods of any parent class, such as the Audi class, which can use base to access the base class Vehicle.run () method. These we can use ILDasm.exe to get answers from the IL code.


.method public hidebysig virtual instance void

ShowResult () cil managed

{

// code size 27 (0x1b)

   .maxstack 8

IL_0000: nop

IL_0001: ldarg.0

// base calls the parent class member

   IL_0002: call instance void Anytao.net.My_Must_net.Car::ShowResult ()

IL_0007: nop

IL_0008: ldarg.0

// base calls a member of the parent class, because Car.Run () is not implemented, so it points to a higher-level parent

   IL_0009: call instance void Anytao.net.My_Must_net.Vehicle :: Run ()

IL_000e: nop

IL_000f: ldstr "It ‘s audi ’s result."

IL_0014: call void [mscorlib] System.Console :: WriteLine (string)

IL_0019: nop

IL_001a: ret

} // end of method Audi :: ShowResult 
IL code


3.3 In-depth analysis



If there are three or more inheritance, then the base of the most subordinate derived class points to that layer? For example. NET system, if base access, should be the direct parent class instance, or the highest level class instance?



First, it is necessary to understand the instantiation order of the class creation process to learn more about the detailed execution of the base mechanism. In general, the instantiation process first instantiates its base class, and so on, until the instantiation of System.Object. Therefore, the class is instantiated and always begins with the call to System.Object.Object (). Thus the instantiation of the class Audi in the example can probably be summarized in the following order, which can be referenced in detail in the sample code analysis.



? Executive System.Object.Object ();



? Execute vehicle.vehicle (string name, int speed);



? Executive Car.car ();



? Execute Car.car (string name, int speed);



? Executive Audi.audi ();



? Executes Audi.audi (string name, int speed).



We can successfully grasp the execution of base and this in the function of the constructor, and further understand its basic function details, on the basis of fully understanding its instantiation order.



The more important analysis below is to analyze the Il decompile code on the basis of the ILDASM.exe tool in order to have a deeper understanding of the application essence behind base and this, so that we can say that there is a basic analysis of the technology.



The main method is executed as follows:


Il analysis base and this execute


Therefore, the override of the parent class method ultimately points to the method member of the highest-level parent class.






4. General rules



? Try to use less or no base and this. In addition to the name collisions of the resolution subclasses and the invocation of other constructors in one constructor, the use of base and this is prone to unnecessary results.



? Using both base and this in a static member is not allowed. The reason is that both base and this access are instances of the class, that is, objects, and static members can only be accessed by the class and cannot be accessed by the object.



? Base is designed to achieve polymorphism.



? You can specify only one constructor using the this or base keyword, which means that this and base cannot be combined on a single constructor.



? In simple terms, base is used to access the overridden base class members in derived classes, and this is used to access members of this class, including, of course, inherited public and protected members.



? In addition to base, another way to access the base class members is to display the type conversions to implement. Only the method cannot be a static method.



The difference between c#base and this


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.