. NET relay and polymorphism in-depth analysis (I)

Source: Internet
Author: User
Tags mscorlib what inheritance

Encapsulation, inheritance, and polymorphism are the three most important characteristics of object-oriented. But it takes a lot of effort to figure out the mysteries of them. I remember that when I was studying C ++ at school, I had been confused about this place. I was still wondering what to do in private mode. How troublesome it was. When it comes to polymorphism, inheritance is even more dizzy. Let's take a closer look at the mysteries.

This article mainly explains the inheritance and Polymorphism in. NET Based on the memory structure, because the memory layout is different, it may be different from the inheritance polymorphism in other languages.

I. Test Questions

 

Class Program
{
Static void Main (string [] args)
{
Cpu c1 = new Cpu ();
C1.fun ();

Cpu c2 = new IntelCpu ();
C2.fun ();

Cpu c3 = new CoreCpu ();
C3.fun ();

IntelCpu c4 = new CoreCpu ();
C4.fun ();
}
}

Class Cpu
{
Public Cpu ()
{
Console. WriteLine ("initialize Cpu ");
}

Public virtual void fun ()
{
Console. WriteLine ("Cpu Method \ n ");
}
}

Class IntelCpu: Cpu
{
Public IntelCpu ()
{
Console. WriteLine ("initialize IntelCpu ");
}

Public override void fun ()
{
Console. WriteLine ("IntelCpu Method \ n ");
}
}

Class CoreCpu: IntelCpu
{
Public CoreCpu ()
{
Console. WriteLine ("initialize CoreCpu ");
}

Public new void fun ()
{
Console. WriteLine ("CoreCpu Method \ n ");

}
}
The above are common questions about inheritance and polymorphism. Maybe many people have a set of methods for doing this kind of questions, which can help you get accurate answers. However, we understand that inheritance and polymorphism are not used to back up formulas, but not for questions. They are used flexibly in the future. So it is necessary to figure out how she implements it internally. It may not work normally, but I think it will be helpful.

 

The basis of inheritance and Polymorphism

What Is Inheritance and polymorphism? There are many comments and explanations in textbooks and on the Internet. I will not explain it here. If you are not familiar with these two concepts, it is difficult for me to read this article.

When studying C ++ in school, the teacher will tell us what inheritance is, and tell us that c ++ has several inheritance methods, such as public, private, and protection. Inheritance improves code reuse. In C #, only public inheritance is required. That is to say, the subclass inherits all fields, methods, and attributes of the parent class (excluding the constructor) and is accessible in the subclass, and the inheritance is passed.

We can call the method of the parent class in the subclass object to achieve code reuse. If we override the method of the parent class object, then our subclass has its own special method, which is different from the parent class behavior, so polymorphism is introduced. The most memorable sentence of polymorphism in C ++ is that it can call the subclass method by pointing to the parent class object. At that time, I thought it was very mysterious. It clearly pointed to the parent class and how to call the subclass. At that time, I was unable to study it in depth due to limited capabilities. Later I looked at COM-related things, talked about interfaces, and talked about method tables, so I had a rough image, it turns out that there is a table that records the method. Of course, moving the pointer can call different methods. However, I have a headache when I see Cpu c2 = new IntelCpu. I cannot figure out whether to call the method by Cpu or IntelCpu.

 

Iii. NET Memory Structure

Before learning about inheritance and polymorphism, it is necessary to understand a memory structure of. NET. Because the call of all objects and methods is inseparable from the thread stack and GC stack. Therefore, we need to first understand how objects are represented in. NET.

1: CLR Domain Structure

Figure-1
After a. NET program is run, three application domains (System domain, shared domain, and default program domain) will be created before the first line of code managed by CLR is executed ). The system domain is responsible for creating and initializing shared domains and default application domains. It loads the system library mscorlib. dll into the shared domain and maintains the implicit or explicit string symbols used within the process range. All code that does not belong to any specific domain is loaded to the system library SharedDomain. Mscorlib, which is required for user code in all application domains. It is automatically loaded to the shared domain. The default domain is an instance of the application domain (AppDomain), where general application code runs. Then we can see the process heap, JIT heap, GC heap, and LOH heap below. The JIT heap stores the compiled code, while GC and LOH stores the object. Then, the object and its respective methods are connected through the Method Tables. This method table is the core of our discussion.
2: Structure of the object in the stack

Figure 2
In the previous. NET study notes, we introduced the distribution and structure of objects in the stack. See NET learning notes (3) ------ system types and general operations.
We know that the object's variables are saved on the thread stack, and the referenced object is saved on the stack. Each object has two additional fields: Synchronous Index block and type object pointer.
What is a type object? We know that when running a program, the CLR system will load three domains, the most important of which is our default program domain. In Figure 1, we can see the structure of the default program domain. When loading a program domain, CLR will construct various custom types of objects based on the metadata in the Assembly. For example, if we define a CPU, We will construct a CPU type object, the object records static fields and methods of this type, pointer to the type object of all instance objects of this type points to this type object (for more details, see CLR Via C # 2nd P90)
Therefore, the process of calling a method is to find the object on the GC stack through the reference variable on the stack, and find its own type-to-object through the type object pointer of this instance object, then, call the corresponding method from the method table of the type object (which generally does not involve inheritance or polymorphism ). This type of object is stored in the default program domain.
3: method table structure

Figure-3
This is a classic image. NET memory structure, the main body of which is the method table we mentioned, the method table is stored in the default program domain through the object type pointer (TypeHandle) it is associated with objects in GC. Actually, the TypeHandle points to the method table, which is placed in the high-frequency heap of the program domain. The Class Loader traverses the metadata of the current class, parent class, and interface, and then creates a method table. During the arrangement, it replaces all the covered Virtual Methods and hidden parent class methods, creates a new slot, and copies the slot as needed. The Virtual Interface diagram of the type object and the number of interfaces are also recorded in the method table. We can also see that there is a white area in the Method Table. This is called the Method Solt Table, which points to the description of each Method, we know that the actual JIT compiled commands are stored in the JIT heap. The static variable storage area is under the method slot table. The method table we mentioned here is the type object mentioned above, and the method that determines the type behavior is saved in the area of the method slot table.
4: method slot table
I have been talking about the memory results of objects. Here I will talk about our key content, the method slot table. From figure-3, we can see the structure of the method slot table. The first four methods are the number of method slots, and the first four methods of any type are always ToString, Equals, GetHashCode, and Finalize. These are virtual methods inherited from System. Object. The following is a virtual method inherited from the base class, followed by its own implementation method, and finally the constructor. The method slot table can be sorted as follows: Virtual Method -- instance method -- constructor method. It is particularly important to note that the instance methods and static methods of the base class do not inherit from the method slot table of the subclass. Here we understand them as before, subclass inherits all non-constructor methods of the parent class. Because inheritance is logical, and here it is a physical structure. That is to say, in a type of method table slot, only the Virtual Methods of the parent class and their own defined methods (no matter the four methods and constructor methods) are available ). Understanding the structure of the method slot table helps you understand the nature of inheritance and polymorphism.
5: Note:
For details about the process and structure of creating objects in. net clr, refer:
In-depth exploration within the. NET Framework learn how CLR creates runtime objects: http://www.microsoft.com/china/MSDN/library/netFramework/netframework/JITCompiler.mspx? Mfr = true

Four SOS extension debugging 
The previous section introduced the structure of an object in CLR, which will help us to find out inheritance and polymorphism. But before explaining inheritance and polymorphism, let's talk about debugging in. Because we need some debugging tools to view the information of the CLR memory objects during runtime. In the program, we use sos for extension debugging. The detailed Command Information is described in MSDN. I also read it online and it will be simple. The following are two reference addresses for you to know how to use them.
Http://www.cnblogs.com/happyhippy/archive/2007/04/11/710930.html
Http://www.rainsts.net/article.asp? Id = 598

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.