How to force overriding a method in a descendant, without having an abstract base class?

前端 未结 14 961
孤城傲影
孤城傲影 2020-12-09 07:24

Question Heading seems to be little confusing, But I will Try to clear my question here.

using System;
using System.Collections.Generic;
usi         


        
14条回答
  •  天涯浪人
    2020-12-09 08:05

    This is a very old thread but the answer given on this question can be usefull. You can force a derived class to have its own implementation of a virtual method/property.

    public class D
    {
        public virtual void DoWork(int i)
        {
            // Original implementation.
        }
    }
    
    public abstract class E : D
    {
        public abstract override void DoWork(int i);
    }
    
    public class F : E
    {
        public override void DoWork(int i)
        {
            // New implementation.
        }
    }
    

    If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

提交回复
热议问题