如何为自己的孩子从父摘要中继承继承的抽象方法?

时间:2019-05-31 17:53:00

标签: c#

我想将方法​​的抽象性从第一个父代传递到该父代的子代。 该方法的主体为空,但我想强制此类的子级和子级的子级完全实现此方法。

我尝试查找类似的问题,但失败了。这可能是由于我不正确理解“抽象”的用法。在这种情况下,我表示歉意。

下面是代码示例:

    public abstract class A
    {
        public abstract void ImportantMethod();
    }

    public abstract class B : A
    {
        public override void ImportantMethod()
        {
            // now this method will still not be used but MUST be implemented in child classes of this class
        }
    }

    public class C : B
    {
        // I can override this method, but it is not enforced - and that is what I am after.
        public override void ImportantMethod()
        {

        }
    }

很明显,我可能以错误的方式使用了抽象,并且有一种特定的方式可以做到这一点,但是我想知道那是什么以及为什么我是一名新程序员。

1 个答案:

答案 0 :(得分:2)

abstract一词表示至少一个继承类必须实现此方法。

  • 如果B确实实现了它,则您无法强迫C这样做。
  • 如果B不实现它,则必须将B声明为抽象,并将实现留给B继承者。
相关问题