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);
}
有时候,上面的东西对我的眼睛看起来不太好。我怎样才能以更好的方式来写这篇文章?
只是有一点补充,不会GetSection()作为NameValueCollection中是比较安全?取决于getSection是否可以返回除NameValueCollection之外的其他内容,这将解释演员。 – dowhilefor
@dowhilefor:这取决于你的意思是“更安全”。如果GetSection(“Servers”)返回某种其他类型的对象时出现错误*(例如在配置或编程中),那么对于异常而言,我绝对没问题。感觉这是一种应该阻止系统出现的情况,而不是试图继续。 –