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

前端 未结 14 904
孤城傲影
孤城傲影 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:06

    This is pretty old, but we have a somewhat similar situation. The base class loads a configuration file and sets up base class defaults. However, the configuration file could also contain default values for inherited classes.

    This is how we got the combined functionality.

    Base class methods

    private void processConfigurationFile()
    {
        // Load and process the configuration file
        // which happens to be an xml file.
        var xmlDoc = new XmlDocument();
        xmlDoc.Load(configurationPath);
    
        // This method is abstract which will force
        // the inherited class to override it.
        processConfigurationFile(xmlDoc);
    }
    
    protected abstract void processConfigurationFile(XmlDocument document);
    
    0 讨论(0)
  • 2020-12-09 08:07

    If you aren't going to create a SalesPerson instance directly, then the simplest thing to do would be to make SalesPerson abstract and that would force any child classes to implement it instead (or be abstract themselves).

    If there is some logic in that method common to all SalesPeople, then you could implement GiveBonus on SalesPerson as a template method. Which calls some abstract method required in any subclasses:

    Which ever way you decide, the only way to force an implementation in a child class is to make the base class abstract.

    0 讨论(0)
提交回复
热议问题