Overriding an abstract method with a virtual one

前端 未结 2 1687
悲&欢浪女
悲&欢浪女 2021-01-18 10:15

I\'m trying to override an abstract method in an abstract class with a virtual method in a child class. I (assumed until now?) understand the difference between abstract and

2条回答
  •  情书的邮戳
    2021-01-18 10:38

    An override method is implicitly virtual (in the sense that it can be overridden in a subclass), unless marked as sealed.

    Observe:

    public class FirstLevelChild1 : TopLevelParent
    {
        protected override void TheAbstractMethod() { }
    }
    
    public class SecondLevelChild1 : FirstLevelChild1
    {
        protected override void TheAbstractMethod() { } // No problem
    }
    
    public class FirstLevelChild2 : TopLevelParent
    {
        protected sealed override void TheAbstractMethod() { }
    }
    
    public class SecondLevelChild : FirstLevelChild2
    {
        protected override void TheAbstractMethod() { } 
        // Error: cannot override inherited member 
        // 'FirstLevelChild2.TheAbstractMethod()' because it is sealed
    }
    

提交回复
热议问题