Overriding an abstract method with a virtual one

前端 未结 2 1662
悲&欢浪女
悲&欢浪女 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:22

    An abstract method is already virtual all the way down the inheritance chain - there's no need to declare it virtual in a subclass to allow the subclass to override it - the subclass can already override it.

    If you don't provide an implementation, the closest implementation (looking down the inheritance list) will be used.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题