我有以下代码行,这给了我NPE的麻烦
ServeUrl = ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment);
Run Code Online (Sandbox Code Playgroud)
当我以下面的方式写这篇文章时,我不再获得NPE
if (ConfigurationManager.GetSection("Servers") != null && ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment) != null)
{
ServeUrl = ((NameValueCollection)ConfigurationManager.GetSection("Servers")).Get(ment);
}
Run Code Online (Sandbox Code Playgroud)
Somwhow,上面的东西对我的眼睛看起来不太好.我怎么能以更好的方式写这个?
我提取一个临时变量:
var section = (NameValueCollection)ConfigurationManager.GetSection("Servers");
if (section != null && section.Get(ment) != null)
{
...
}
Run Code Online (Sandbox Code Playgroud)
甚至:
var section = (NameValueCollection)ConfigurationManager.GetSection("Servers");
if (section != null)
{
var url = section.Get(ment);
if (url != null)
{
ServeUrl = url;
}
}
Run Code Online (Sandbox Code Playgroud)
如果GetSection返回null,你想做什么?你真的可以继续吗?
| 归档时间: |
|
| 查看次数: |
4229 次 |
| 最近记录: |