2014-10-10 3 views
0

자식 클래스가 부모 클래스의 메서드를 재정의하는 것을 어떻게 알 수 있습니까? 현재 부모 클래스에서 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); 
    } 
} 

답변

0

당신은 Class_A에서 아무것도하지 않는 CheckData()을 구현할 수 있습니다 (그래서 더 이상 추상적 아니다). 그런 다음 관련 Class_B 's에서이 구현을 재정의합니다. Class_C에서 if 문을 제거하십시오. 이 방법으로 항상 CheckData()이 호출됩니다. 기본적으로 클래스는 클래스에서 무언가를하고 싶지 않으면 아무 것도하지 않습니다.

+0

작은 참고 사항 : Class_A는 무언가를 수행해야하며 false를 반환합니다 (또는 true). – David

관련 문제