【问题标题】:Why the output of following program is => BC::Display BC::Display BC::Display为什么以下程序的输出是 => BC::Display BC::Display BC::Display
【发布时间】:2015-08-01 11:05:41
【问题描述】:
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”?

【问题讨论】:

标签: c# overriding


【解决方案1】:

如果您在 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

您必须在DCTC 中使用override 而不是virtual,否则您正在执行new virtual 并创建一个不会“覆盖”BC.Display 的新方法,但那是只是“隐藏”它。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      相关资源
      最近更新 更多