简体   繁体   中英

C# : calling base method from overridden one

With those classes:

public abstract class T_BaseClass
{
    public virtual void m_canvas()
    {
        Console.WriteLine("canvas method called from template.");            
    }
}

public class C_ChildT : T_BaseClass
{
    public override void m_canvas()
    {
        base.m_canvas();
        Console.WriteLine("canvas method called from child template.");
    }
}

What is the differences between those two implementations?

Difference between

C_ChildT mychildclass = new C_ChildT();

and

T_BaseClass mychildclass1 = new C_ChildT();


mychildclass.m_canvas();
mychildclass1.m_canvas();

Hope it looks better M.Skeet.

Thank you for your answer.

Basically, you don't need a deep understanding of inheritance to work with it. The minimum, that you should know is that the last child of inheritance sequence methods is called, when you call any method on an object. Also you should know that variable type and object type are different things, and you can store an object of child types in a variable of parent type. So, in your example you have two variables with C_ChildT and T_BaseClass types. But both objects are C_ChildT type. So when you call m_canvas() on each of them, you will call the C_ChildT implementation of m_canvas() in both cases.

Under the hood, when you call a virtual method, your runtime evironment sees, that the method is marked with the virtual keyword, so it (runtime environment) starts looking for overrriding of this method in the most derived class. You can read more about it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM