2012-10-08 1 views
1

나는 다음과 같은 클래스가 :콜링 기본 클래스 생성자

public abstract class BusinessRule 
{ 
    public string PropertyName { get; set; } 
    public string ErrorMessage { get; set; } 

    public BusinessRule(string propertyName) 
    { 
     PropertyName = propertyName; 
     ErrorMessage = propertyName + " is not valid"; 
    } 

    public BusinessRule(string propertyName, string errorMessage) 
     : this(propertyName) 
    { 
     ErrorMessage = errorMessage; 
    } 
} 

그리고

public class ValidateId : BusinessRule 
{ 
    public ValidateId(string propertyName) : base(propertyName) 
    { 
     ErrorMessage = propertyName + " is an invalid identifier"; 
    } 

    public ValidateId(string propertyName, string errorMessage) 
     : base(propertyName) 
    { 
     ErrorMessage = errorMessage; 
    } 

    public override bool Validate(BusinessObject businessObject) 
    { 
     try 
     { 
      int id = int.Parse(GetPropertyValue(businessObject).ToString()); 
      return id >= 0; 
     } 
     catch 
     { 
      return false; 
     } 
    } 
} 

그리고 고객 클래스 내에서

public class Customer : BusinessObject 
{ 
    public Customer() 
    { 
     AddRule(new ValidateId("CustomerId")); 
    } 
} 

나는 새로운 비즈니스 규칙을 추가하고를 ValidateId의 생성자가 기본 클래스 생성자를 호출하면 생성자를 호출하여 ValidateId를 호출합니다. 내가 조금 혼란스러워지기 시작한 곳이다.

ValidateId 생성자가 달성하려는 작업을 수행 할 수있는 경우 왜 기본 클래스 생성자를 호출해야합니까?

이 기본 생성자에 있습니다 :

 PropertyName = propertyName; 
     ErrorMessage = propertyName + " is not valid"; 

이이 ValidateId 생성자에 :의

ErrorMessage = propertyName + " is an invalid identifier"; 

하나 ValidateId 생성자와 기본 생성자 모두 뭔가에 오류 메시지를 설정하는 것입니다 ErrorMessage는 사용자에게 오류를 표시하는 데 사용됩니까?

또한 나는 : base(propertyName)를 제거하지 분명히 난 그냥 Businessrule에 매개 변수가없는 생성자를 추가하고 ValidateId 생성자에서 모든 것을 구현할 수있다, 나는 BusinessRule이 매개 변수가없는 생성자 오류 메시지가 포함되어 있지 않습니다 얻을 기본 생성자를 호출하지만 무엇을 알고 싶다면 기본 생성자를 호출하거나 호출하지 않는다는 장점/의미는 무엇입니까?

감사

답변

5

왜 ValidateId 생성자 내가 달성하기 위해 노력하고 일을 할 수있을 때 기본 클래스 생성자를 호출해야합니까? 달리 어떤 수준 (문자열을 자신을 초기화하고 매개 변수를 공공 ValidateId을 검증 할 기회가없는 것 "생략"-

당신 항상상속 계층 구조의 모든 수준에서 생성자를 통과해야 propertyName) : base (propertyName) { ErrorMessage = propertyName + "잘못된 식별자입니다."; }.

FileStream에서 파생 된 클래스를 만들면 기존 FileStream 생성자를 건너 뛸 수 있다고 상상해보십시오. 어디에서 데이터를 가져 옵니까?

ValidateId(string propertyName)가로 구현되어야한다는 것을 나에게 보인다

public ValidateId(string propertyName) 
    : base(propertyName, propertyName + " is an invalid identifier") 
{ 
} 

만의 코드 하나 조각 오류 메시지가 설정 될 필요가 - 개인적으로 내가 실제로 BusinessRule 내에서 세터 비공개 것, 심지어는 별도의 읽기 전용 필드를 사용하여 getter 만 제공 할 수도 있습니다.

+0

설명해 주셔서 감사합니다. – 03Usr

0

매개 변수없이 BusinessRule() 생성자를 작성하십시오.validateId()에서 base()를 호출하십시오.