为什么出人意料的答案来了? [英] why is the unexpected answering coming ?

查看:95
本文介绍了为什么出人意料的答案来了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class A
{
    Public virtual void WhoAreYou() 
    { 
        Console.WriteLine("I am an A");
    }
}

Class B: A 
{
    Public override void WhoAreYou() 
    { 
        Console.WriteLine("I am a B");
    }
}

Class C: B 
{
    Public new virtual void WhoAreYou()
    { 
        Console.WriteLine("I am a C");
    }
}

Class D: C 
{
    Public override void WhoAreYou()
    { 
        Console.WriteLine("I am a D");
    }
}
  
C c = new D ();
c.WhoAreYou();			// "I am a D"



但是,当我执行以下操作时,它将给出此答案.为什么?



But when I do the following, it gives this answer. Why ?

A a =  new D ();
a.WhoAreYou();			// "I am a B" !!



我的问题是:它应该显示:我在D中" ....但事实并非如此.为什么?请解释.



My question is : It should have shown : "I am in D"....but it is not. WHY? Please Explain.

推荐答案

您在C中定义构造函数时使用了new关键字.
与原始继承层次结构脱离".

A找到的最重要的方法是B的WhoAreYou() ,因为C和D的WhoAreYou() 处于不同的层次结构.
You have used the new keyword while defining the constructor in C.
That ''breaks away'' from the original inheritance hierarchy.

The most overridden method that A finds is B''s WhoAreYou() as C and D''s WhoAreYou() are in a different hierarchy.


这篇关于为什么出人意料的答案来了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆