2011-12-04 274 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

是的。通常的做法是在構造函數中驗證參數,如果它們無效則拋出異常。

0

這很好。構造函數不返回任何東西,那麼如果出現問題,你還會怎麼知道?你可以有一個布爾設置它爲一些未初始化的狀態,但我會去例外。

另外:

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

感謝您對IsNullOrEmpty方法的提示! – Chris

0

在這種情況下,你可以使用靜態方法string.IsNullOrEmpty(command鍵):

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

請注意,還有一個方法string.IsNullOrWhitespace()來檢查字符串是否僅包含空格。 –

0

這就是如果你看看通過框架源代碼,微軟做了什麼,所以我懷疑它是完全有效的。

0

如果您驗證一個構造函數和拋出異常內如果出現錯誤,這是完全正常的。

相關問題