【问题标题】:Virtual, Override and new keys in inheritance hierarchy [duplicate]继承层次结构中的虚拟、覆盖和新键[重复]
【发布时间】:2021-03-08 13:23:33
【问题描述】:

我有以下代码:

   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# .net inheritance polymorphism


【解决方案1】:

InvokeAnimal 上是虚拟的,被Dog 覆盖,并且隐藏Dobberman (SIC)

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

所以绑定如下:

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(); 

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2015-07-09
    • 1970-01-01
    相关资源
    最近更新 更多