【问题标题】:Why is this virtual method called? [duplicate]为什么要调用这个虚方法? [复制]
【发布时间】:2017-08-24 02:17:39
【问题描述】:

我写了一个基类和两个派生类:

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");
        }
    }

然后创建一个由 Base 变量引用的 derived2 实例。然后调用 fn() 方法:

class Program
    {
        static void Main(string[] args)
        {
            Base b = new Derived2();
            b.fn();
            Console.Read();
        }
    }

结果是调用了Derived1 Class的fn()。

据我所知,如果调用了虚方法,CLR会在运行时类型的方法表中查找该方法,也就是Derived2;如果调用了非虚拟方法,ClR 会在变量类型为 Base 的方法表中查找它。但是为什么会调用Derived1的方法呢?

答案“因为 Derived1 覆盖了 Base 的 fn()”不足以澄清我的困惑。请给我更多的细节。

【问题讨论】:

    标签: c# clr


    【解决方案1】:

    虚方法调用在reference中解释如下:

    当调用虚方法时,对象的运行时类型为 检查覆盖成员。 最重要的成员 派生类被称为,它可能是原始成员,如果没有 派生类已覆盖该成员。

    由于 Derived2 类使用“new”关键字隐藏基方法,CLR 将在最派生类中查找重写成员,即 Derived1 并执行其方法。

    【讨论】:

    • 我又做了一个测试:
    猜你喜欢
    • 2012-08-24
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    相关资源
    最近更新 更多