2012-12-11 115 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逻辑运算符