为什么以下程序的输出是=> BC ::显示BC ::显示BC ::显示

时间:2015-05-20 09:27:55

标签: c# method-overriding

class BC
{
    public virtual void Display()
    {
        System.Console.WriteLine("BC::Display");
    }
}

class DC : BC
{
    public virtual void Display()
    {

        System.Console.WriteLine("DC::Display");

    }
}

class TC : DC
{
    public virtual void Display()
    {
        System.Console.WriteLine("TC::Display");
    }
}



class Program
{
   public static void Main()
   {
       BC b;
       b = new BC();
       b.Display();

       b = new DC();
       b.Display();

       b = new TC();
       b.Display();


   }
}

为什么输出不是“BC :: Display DC :: Display TC :: Display”?

2 个答案:

答案 0 :(得分:0)

只需要将基类中的方法标记为virtual。派生类中的方法应标记为override,否则它们会隐藏基础方法。由于它们是“不同的”方法,而b的类型为BC,编译器会将所有调用路由到BC.Display

答案 1 :(得分:0)

如果在Visual Studio中编译它,您将收到以下警告:

Warning 2   'Workbench.Program.DC.Display()' hides inherited member 'Workbench.Program.BC.Display()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. C:\Users\Alberti\Documents\Visual Studio 2013\Projects\Workbench\Workbench\Program.cs   328 29  Workbench
Warning 3   'Workbench.Program.TC.Display()' hides inherited member 'Workbench.Program.DC.Display()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. C:\Users\Alberti\Documents\Visual Studio 2013\Projects\Workbench\Workbench\Program.cs   338 29  Workbench

您必须在overridevirtual中使用DC代替TC,否则您正在执行new virtual并创建一个新方法,而不是{39} ; t"覆盖" BC.Display,但这只是"隐藏"它

这里有一个很好的解释:https://stackoverflow.com/a/6162547/613130关于virtual/overridenew

之间的区别