C # A derived class Class IL strong base class or actually turn can invoke a method of an example of a derived class

We all know that in C #, if class B inherits from class A, B if an object is of type A, but after conversion type, this object is unable to call a method belonging to B type, the following examples:

Class group A:

public class A
{
}

Derived class B:

public class B : A
{
    public void Test()
    {
        Console.WriteLine("Hello World!");
    }
}

If we write:

A a = new B();
a.Test();

We will find the compiler is not passed, the following errors:

 

Recently I looked at "C # from phenomenon to essence." Written on the book "so that the object is achieved by a method B IL can call," I reflected for a long time to think of an example, IL code is as follows:

.assembly extern mscorlib
{
    auto
}
.assembly MyTest {}
.module MyTest.exe
.class public A
{
    .method public specialname void .ctor()
    {
        ldarg.0
        call instance void [mscorlib]System.Object::.ctor()
        ret
    }
}
.class public B extends A
{
    .method public specialname void .ctor()
    {
        ldarg.0
        call instance void A::.ctor()
        ret
    }
    
    .method public void Test()
    {
        ldstr "helle world!"
        call void [mscorlib]System.Console::WriteLine(string)
        ret
    }
}
.method public static void Main()
{
    .entrypoint
    .locals (class A V_0)
    newobj instance void B::.ctor()
    stloc.0
    ldloc.0
    call instance void B::Test()
    ret
}

The code is written to a test.il empty file, and then open the "VS2015 developer command prompt", enter "ilasm test.il", as follows:

 

 Executed successfully, generate a "test.exe", execute the command in the form a bit, as shown below:

 

 

 

As the storyteller said IL method of the object is executed when the runtime object allows compilation.

Guess you like

Origin www.cnblogs.com/Jeffrey-Chou/p/11914703.html