知道父类的子类重写方法而没有附加标志

本文关键字:标志 方法 父类 子类 重写 | 更新日期: 2023-09-27 18:26:14

如何知道子类正在重写其父类的方法?目前,我正在使用布尔标志,该标志在父类上设置为false,当子类覆盖它时,子类必须设置该标志。当它发挥作用时,我想知道是否有更清洁的解决方案来解决这个问题。

// The parent class
public Class_A
{
    protected bool _hasCheckData = false;
    public bool HasCheckData
    {
        get { return _hasCheckData; }
    }
    public abstract bool CheckData(File fileToCheck)
    {
        return true;
    }
}
// Lot's of children from class A, this is one of them
public Class_B : Class_A
{
    public override bool CheckData(File fileToCheck)
    {
        // the following line will be duplicated for all Class_A's children 
        // who implemented the checking of the file. How to avoid this?
        _hasCheckData = true; 
        // checking the file
        // and return the result
    }
}
public Class_C
{
    public void Test(File fileToCheck)
    {
       Class_B fileAbcChecker = new Class_B();
       if (fileAbcChecker.HasCheckData)
           fileAbcChecker.CheckData(fileToCheck);
    }
}

知道父类的子类重写方法而没有附加标志

您可以实现一个在class_a中什么都不做的CheckData()(因此它不再是抽象的)。然后,在相关的Class_B中,覆盖此实现。在Class_C中,删除if语句。通过这种方式,CheckData()总是被调用。默认情况下,它什么都不做,除非类希望用它做点什么。