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

时间:2014-10-10 02:00:52

标签: c# inheritance override abstract

我如何知道子类覆盖其父类的方法?目前我正在使用boolean标志,该标志在父类上设置为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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

相关问题