I write a base class and two derived classes:
class Base
{
public virtual void fn()
{
Console.WriteLine("base fn");
}
}
class Derived1 : Base
{
public override void fn()
{
Console.WriteLine("derived1 fn");
}
}
class Derived2 : Derived1
{
public new void fn()
{
Console.WriteLine("derived2 fn");
}
}
then create an instance of derived2, referenced by a Base variable. Then call the fn() method:
class Program
{
static void Main(string[] args)
{
Base b = new Derived2();
b.fn();
Console.Read();
}
}
the result is that the fn() of Derived1 Class is called.
As far as I know, if a virtual method is called, CLR will look for the method in the method table of the runtime type, which is Derived2; if a non-virtual method is called, ClR will look for it in the method table of the variable type which is Base. But why it calls the method of Derived1?
The Answer "Because Derived1 overrides the fn() of Base" is not enough to clarify my puzzle. Please give me more detail.