为什么调用这个虚方法?
Why is this virtual method called?
我写了一个基础 class 和两个派生的 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");
}
}
然后创建 derived2 的实例,由 Base 变量引用。然后调用fn()方法:
class Program
{
static void Main(string[] args)
{
Base b = new Derived2();
b.fn();
Console.Read();
}
}
结果调用了Derived1Class的fn()
据我所知,如果调用虚方法,CLR会在运行时类型的方法table中寻找该方法,即Derived2;如果调用了非虚方法,ClR会在变量类型为Base的方法table中查找。但是为什么会调用Derived1的方法呢?
答案"Because Derived1 overrides the fn() of Base" 不足以澄清我的困惑。请给我更详细的信息。
虚方法调用在reference中解释如下:
When a virtual method is invoked, the run-time type of the object is
checked for an overriding member. The overriding member in the most
derived class is called, which might be the original member, if no
derived class has overridden the member.
由于 Derived2 class 使用 "new" 关键字隐藏了基本方法,CLR 将寻找最派生的 class 中的重写成员,即 Derived1 并执行其方法。
我写了一个基础 class 和两个派生的 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");
}
}
然后创建 derived2 的实例,由 Base 变量引用。然后调用fn()方法:
class Program
{
static void Main(string[] args)
{
Base b = new Derived2();
b.fn();
Console.Read();
}
}
结果调用了Derived1Class的fn()
据我所知,如果调用虚方法,CLR会在运行时类型的方法table中寻找该方法,即Derived2;如果调用了非虚方法,ClR会在变量类型为Base的方法table中查找。但是为什么会调用Derived1的方法呢?
答案"Because Derived1 overrides the fn() of Base" 不足以澄清我的困惑。请给我更详细的信息。
虚方法调用在reference中解释如下:
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
由于 Derived2 class 使用 "new" 关键字隐藏了基本方法,CLR 将寻找最派生的 class 中的重写成员,即 Derived1 并执行其方法。