C # Base and this

Source: Internet
Author: User
Tags mscorlib

Tag: Add text log to implement local analysis instance system compilation

? 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 ()
{
}
Qualify a member that is hidden by a similar name
Public Vehicle (string name, int speed)
{
THIS.name = name;
This.speed = speed;
}
public virtual void Showresult ()
{
Console.WriteLine ("The top speed of {0} was {1}.", name, speed);
}
public void Run ()
{
Passing the current instance parameters
Action.torun (this);
}
Declares an indexer, which must be this, so that an object can be indexed like an array
public string this[int param]
{
Get{return Array[param];}
Set{array[param] = value;}
}
}
public class Car:vehicle
{
Derived class and base class communication, implemented as base, the base class is first called
Specifies the base class constructor that should be called when creating an instance of a derived class
Public Car ()
: Base ("Car", 200)
{ }

Public Car (string name, int speed)
: This ()
{ }

public override void Showresult ()
{
Calling a method on a base class that has been overridden by another method
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 ()
{
As you can see from the three-tier inheritance, 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 ();
}
}
}

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.



Showresult () CIL managed
{
Code size (0x1b)
. maxstack 8
il_0000: NOP
il_0001: ldarg.0
Base Call Parent class member
IL_0002: call instance void Anytao.net.my_must_net.car::showresult ()
il_0007: NOP
il_0008: ldarg.0
Base calls the parent class member because no Car.run () is implemented, so point to the higher-level parent class
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

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:


. method public hidebysig static void Main (string[] args) cil managed
{
. entrypoint
Code size (0X3D)
. maxstack 3
. Locals init (class Anytao.net.My_Must_net.Audi V_0)
Il_0000:nop
Use the newobj directive to create a new object and call the constructor class.
il_0001:newobj instance void Anytao.net.my_must_net.audi::.ctor ()
il_0006:stloc.0
il_0007:ldloc.0
il_0008:ldc.i4.1
Il_0009:ldstr "A6"
Il_000e:callvirt instance void Anytao.net.my_must_net.vehicle::set_item (Int32,
String
Il_0013:nop
il_0014:ldloc.0
il_0015:ldc.i4.2
Il_0016:ldstr "A8"
Il_001b:callvirt instance void Anytao.net.my_must_net.vehicle::set_item (Int32,
String
Il_0020:nop
il_0021:ldloc.0
il_0022:ldc.i4.1
Il_0023:callvirt Instance String Anytao.net.my_must_net.vehicle::get_item (Int32)
Il_0028:call void [Mscorlib]system.console::writeline (String)
Il_002d:nop
il_002e:ldloc.0
Il_002f:callvirt instance void Anytao.net.my_must_net.vehicle::run ()
Il_0034:nop
il_0035:ldloc.0
Base. Showresult finally calls the method of the highest parent class vehicle,
Instead of the direct parent class Car.showresult () method, this should be a concern
Il_0036:callvirt instance void Anytao.net.my_must_net.vehicle::showresult ()
Il_003b:nop
Il_003c:ret
}//End of method Basethistester::main

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.

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.