2011-12-04 3 views
2

매개 변수가 유효한 데이터와 함께 전달되지 않으면 개체의 인스턴스화를 중단하는 가장 좋은 방법입니까?생성자 및 예외 발생

protected Command(string commandKey) 
{ 
    if(commandKey == null) throw new ArgumentNullException("commandKey", "Command Key cannot be null as it is required internally by Command"); 
    if(commandKey == "") throw new ArgumentException("Command Key cannot be an empty string"); 
    CommandKey = commandKey; 
} 

답변

1

예. 생성자에서 인수의 유효성을 검사하고 유효하지 않은 경우 예외를 throw하는 것이 일반적입니다.

0

괜찮습니다. 생성자는 아무 것도 반환하지 않으므로 잘못된 것이 있는지 어떻게 알 수 있습니까? 초기화되지 않은 상태로 설정할 수있는 bool을 가질 수는 있지만 예외가있을 것입니다. 또한

:

if(String.IsNullOrEmpty(commandKey)) //throw exectpion 
+1

IsNullOrEmpty 메서드에 대한 정보 주셔서 감사합니다! – Chris

0

당신이 정적 메소드 string.IsNullOrEmpty (commandKey) 사용할 수 있습니다이 경우 :

protected Command(string commandKey) 
{ 
    if(string.IsNullOrEmpty(commandKey)) 
     throw new ArgumentException("commandKey"); 
    //something 
} 
+0

문자열이 공백으로만 구성되어 있는지 검사하는 메서드 string.IsNullOrWhitespace()가 있습니다. –

0

를 이것은 당신이 프레임 워크의 소스 코드를 보면 마이크로 소프트가 무엇을하는지 정확히 , 나는 그것이 완벽하게 유효하다고 생각한다.

0

생성자 내부에서 유효성을 검사하고 문제가 발생하면 예외를 throw하면 완벽하게 문제가 없습니다.