2011-04-18 51 views
1

與以下代碼片段相當的速記是什麼?等效縮寫

if (strValue == ""){ 
    throw new Exception("Mandatory 'strValue' parameter empty"); 
} 
+4

這已經很短了。任何更短的內容都可能導致無法閱讀。 – 2011-04-18 20:34:25

回答

9

它可能儘可能短,除非刪除空格和大括號(並犧牲了可讀性)。

至於正確性...這可能會更好:

.NET 4.0:

if (string.IsNullOrWhiteSpace(strValue)){ 
    throw new ArgumentException("Mandatory 'strValue' parameter empty"); 
} 

.NET < 4.0:

if (string.IsNullOrEmpty(strValue)){ 
    throw new ArgumentException("Mandatory 'strValue' parameter empty"); 
} 

另外請注意,這是不好的做法,簡單地扔Exception - 從BCL中選擇適當的異常類(如果存在的話)或自定義的類(如果不存在的話)會更好。 (謝謝@djacobson)

+0

如果你拋出一個'ArgumentException'而不是一個'Exception',它可能會*更好*。 – 2011-04-21 19:57:07

+0

@djacobson - 公平點。答覆修正。 – Oded 2011-04-21 20:01:40

3

您可以使用代碼合同。

您也可以使用string.IsNullOrWhitespace()

Contract.Requires(string.IsNullOrEmpty(strValue), "** fancy localized message here ***"); 
+0

「更短」的原因是您可以有條件地將其從發佈版本中刪除,並將檢查保留在已檢查的版本中。 – GregC 2011-04-18 20:48:10

5
if(strValue=="")throw new Exception("Mandatory 'strValue' parameter empty"); 

所有你能做的就是去掉括號和空格:)

+0

我想你是對的! (如果你真的想要相當):) – 2011-04-18 20:37:02

1

它已經短。而不是做strValue ==「」,我會做String.Empty或String.NullOrEmpty,我不記得哪一個可用於.NET。

1

不會變得更短,但如果需要更少的行:

if (String.IsNullOrWhitespace(strValue)) throw new Exception("Mandatory 'strValue' parameter empty"); 
4

隨着空校驗,我想你想和使用的ArgumentException:

ThrowIfNullOrEmpty(strValue, "strValue"); 

... 

private void ThrowIfNullOrEmpty(string parameterValue, string parameterName) 
{ 
    if String.IsNullorEmpty(parameterValue) 
    { 
     throw new ArgumentException("Mandatory 'strValue' parameter empty", 
            parameterName); 
    } 
} 

顯然只有當你在做多幾次這樣更加有用。

+0

+1:偉大的重用。 – 2011-04-18 20:39:14

+0

會做出很好的擴展方法,可能會將parameterValue參數放入表達式中並將名稱拉回來以消除對parameterName參數的需要。 (你已經拋出了一個異常,這是多少開銷?:)) – asawyer 2011-04-18 20:45:29

+0

@asawyer:嗯。在這種情況下,擴展方法感覺不對。我正在採取的行動是在方法的上下文中 - 現在,如果我可以對*方法*本身做一個擴展方法...我猜,它正在接近代碼合同。 – 2011-04-18 20:47:43

0

假設你正在嘗試寫更多的防守代碼,你可以使用Trace.Assert

Trace.Assert(strValue != "", "Mandatory 'strValue' parameter is not empty"); 

或者你可以使用Fluent Validation庫封裝更復雜的驗證。

1

你幾乎就像你可以得到的一樣短。我建議使用IsNullOrEmpty字符串函數來檢查一個空字符串。另外,在您的異常處理中可能更具體,並拋出ArgumentException

if (String.IsNullOrEmpty(strValue)) { throw new ArgumentException("strValue must not be null or empty") }; 
+0

+1,用於提及ArgumentException。 – juharr 2011-04-18 21:14:12