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

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

    Use dependency injection. Create a BonusCalculator class:

    public abstract class BonusCalculator
    {
       public abstract decimal CalculateBonus(Employee e)
    }
    

    In your base class:

    private BonusCalculator Calculator { get; set; }
    
    public void GiveBonus()
    {
       Bonus = Calculator.CalculateBonus(this)
    }
    

    In your implementation's constructor:

    public SomeKindOfEmployee()
    {
        Calculator = new SomeKindOfEmployeeBonusCalculator();
    }
    

    Someone implementing a Person subclass now has to explicitly provide it with an instance of a BonusCalculator (or get a NullReferenceException in the GiveBonus method).

    As an added, er, bonus, this approach allows different subclasses of Person to share a bonus-calculation method if that's appropriate.

    Edit

    Of course, if PTSalesPerson derives from SalesPerson and its constructor calls the base constructor, this won't work either.

提交回复
热议问题