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

前端 未结 14 979
孤城傲影
孤城傲影 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 07:58

    I feel like this indicates that your implementation really has two parts: a partial implementation that goes in the base class, and a missing completion to that implementation that you want in the sub class. Ex:

    public abstract class Base
    {
       public virtual void PartialImplementation()
       {
          // partial implementation
       }
    }
    
    public sealed class Sub : Base
    {
       public override void PartialImplementation()
       {
          base.PartialImplementation();
          // rest of implementation
       }
    }
    

    You want to force the override, since the initial implementation is incomplete. What you can do is split your implementation into two parts: the implemented partial part, and the awaiting-implementation missing part. Ex:

    public abstract class Base
    {
       public void PartialImplementation()
       {
          // partial implementation
    
          RestOfImplementation();
       }
    
       // protected, since it probably wouldn't make sense to call by itself
       protected abstract void RestOfImplementation();      
    }
    
    public sealed class Sub : Base
    {
       protected override void RestOfImplementation()
       {
          // rest of implementation
       }
    }
    

提交回复
热议问题