Internal working of virtual and override in C#? [duplicate]
Possible Duplicate:
Internal Workings of C# Virt开发者_如何学Goual and Override
I want to know how the virtual and override is working in c#. For example
class Base
{
public virtual void Display()
{}
}
class Derived: Base
{
public override void Display()
{}
}
Main()
{
Base obj = new Derived();
obj.Display();
}
It will call derived class "Display" method.
How the object knows it should call Derived.Display(), not Base.Display()?
when encountered with a virtual method the IL emitted will be callvirt
which checks if the method has been overriden in any of its derived classes at run time.That is the reason why Display in derived class will get called.
You can check the IL emitted to see.
It will execute the closest definition of the method. However, if you call base.Display
from Derived.Display
, it will execute the base class's version.
Note:
Also, because Display
is protected, it cannot be called from where you are using it.
精彩评论