2012-12-11 42 views
0

我有下面的代碼行,這是給我的NPE方式來檢查空值,如果條件

ServeUrl = ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment); 

的麻煩。當我寫這篇文章在下面的路上,我不再讓NPE

if (ConfigurationManager.GetSection("Servers") != null && ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment) != null) 
          { 
           ServeUrl = ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment); 
          } 

有時候,上面的東西對我的眼睛看起來不太好。我怎樣才能以更好的方式來寫這篇文章?

回答

4

我會抽出一個臨時變量:

var section = (NameValueCollection)ConfigurationManager.GetSection("Servers"); 
if (section != null && section.Get(ment) != null) 
{ 
    ... 
} 

甚至:

var section = (NameValueCollection)ConfigurationManager.GetSection("Servers"); 
if (section != null) 
{ 
    var url = section.Get(ment); 
    if (url != null) 
    { 
     ServeUrl = url; 
    } 
} 

你想怎麼做,如果GetSection返回null關係嗎?你能否居然繼續?

+0

只是有一點補充,不會GetSection()作爲NameValueCollection中是比較安全?取決於getSection是否可以返回除NameValueCollection之外的其他內容,這將解釋演員。 – dowhilefor

+0

@dowhilefor:這取決於你的意思是「更安全」。如果GetSection(「Servers」)返回某種其他類型的對象時出現錯誤*(例如在配置或編程中),那麼對於異常而言,我絕對沒問題。感覺這是一種應該阻止系統出現的情況,而不是試圖繼續。 –

1
  1. !=意味着not equal to==意味着equal to

  2. 如果您不能使用NULL可以使用""

與邏輯應用的條件,然後它是沒有得到即使然後你想要什麼:

  1. 條件將false,你也用AND邏輯運算符