简体   繁体   English

抽象类继承混淆

[英]Abstract Class Inheritance Confusion

I have a D class inherits from C abstract class and writing to console related message. 我有一个D类继承自C抽象类并写入控制台相关的消息。 I expect to see "D" on my console window but it writes "B". 我希望在我的控制台窗口看到“D”,但它会写“B”。 I think virtual keyword in C class breaks the rule. 我认为C类中的虚拟关键字违反了规则。 I didn't understand why. 我不明白为什么。 Can anyone explain? 谁能解释一下?

  class Program
{
    static void Main(string[] args)
    {
        A obj = new D();
        obj.Write();
        Console.Read();
    }
}

public abstract class A
{
    public virtual void Write()
    {
        Console.WriteLine("A");
    }
}

public abstract class B : A
{
    public override void Write()
    {
        Console.WriteLine("B");
    }
}

public abstract class C : B
{
    public virtual void Write()
    {
        Console.WriteLine("C");
    }
}

public class D : C
{
    public override void Write()
    {
        Console.WriteLine("D");
    }
}

The problem is that C does not override the function from class A . 问题是C不会覆盖A类的功能。 The compiler gives you a warning the the new keyword is required. 编译器会警告您需要new关键字。 If you also use override in class C , it works like you expected. 如果你也在C类中使用override ,它就像你期望的那样工作。

Or if you replace A obj = new D(); 或者如果你替换A obj = new D(); with D obj = new D(); D obj = new D(); , you would get the same result. ,你会得到相同的结果。

Your compiler already does a pretty good job here if you listen to it: 如果你听它,你的编译器在这里做得很好:

warning CS0114:

'C.Write()' hides inherited member 'B.Write()'.

To make the current member override that implementation, add the override keyword. 要使当前成员覆盖该实现,请添加override关键字。

Otherwise add the new keyword. 否则添加关键字。

The fact that you used virtual instead of override on C will result in the default behaviour of new for this method, breaking the inheritance chain. 您在C上使用virtual而不是override的事实将导致此方法的默认行为new ,从而破坏了继承链。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM