首页 > 解决方案 > 继承层次结构中的虚拟键、覆盖键和新键

问题描述

我有以下代码:

   class Animal
    {
        public virtual void Invoke()
        {
            Console.WriteLine("Animal");
        }
    }
    class Dog : Animal
    {
        public override void Invoke()
        {
            Console.WriteLine("Dog");
        }
    }
    class Dobberman : Dog
    {
        public new void Invoke()
        {
            Console.WriteLine("Dobberman");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Animal dog = new Dobberman();
            dog.Invoke();
            Dobberman dog2 = new Dobberman();
            dog2.Invoke();
        }
    }

为什么它会在第一个输出中打印“Dog”?为什么第二个是“杜伯曼”?引擎盖下发生了什么?

标签: c#.netinheritancepolymorphism

解决方案


Invoke是虚拟的Animal,被 覆盖Dog,并被(SIC)隐藏Dobberman

请记住,方法在编译时绑定,然后在运行时查找虚拟方法的覆盖。

所以绑定如下:

Animal dog = new Dobberman(); 
// binds to Dog.Invoke since the variable type is Animal, 
// the runtime type is Dog
// and Dog overrides Animal.Invoke
dog.Invoke();  

Dobberman dog2 = new Dobberman();
// binds to Dobberman.Invoke since the variable type is Dobberman
dog2.Invoke(); 

推荐阅读