我想获取服务器地址值,但我在Alert方法中收到了null reference exception
:
Values.Server.Key [" CollectorServer"]。地址 - >空引用 例外
我的app.config看起来像这样:
<configSections>
<section requirePermission="false" name="serverlist" type="SampleConsole.CustomAppTest, SampleConsole"></section>
</configSections>
<serverlist>
<add name="CollectorServer" address="127.0.0.1"></add>
</serverlist>
我的自定义配置部分如下所示:
namespace SampleConsole
{
public class CustomAppTest
{
public void Alert()
{
Console.WriteLine(Values.Server.Key["CollectorServer"].Address);
}
}
public class Values
{
public static ServerValues Server = ConfigurationManager.GetSection("serverlist") as ServerValues;
}
public class ServerValues : ConfigurationSection
{
[ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
public ServerCollection Key
{
get { return (ServerCollection)this[""]; }
set { this[""] = value; }
}
}
public class ServerCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new ServerElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ServerElement)element).Name;
}
public new ServerElement this[string elementName]
{
get
{
return this.OfType<ServerElement>().FirstOrDefault(item => item.Name == elementName);
}
}
}
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)base["name"]; }
set { base["name"] = value; }
}
[ConfigurationProperty("address", IsRequired = true)]
public string Address
{
get { return (string)base["address"]; }
set { base["address"] = value; }
}
}}
答案 0 :(得分:1)
试试这个...... 使您的应用配置如下。
<serverfulllist>
<serverlist>
<add name="CollectorServer" value="127.0.0.1"/>
</serverlist>
</serverfulllist>
NameValueCollection address =
ConfigurationManager.GetSection("serverfulllist/serverlist")
as System.Collections.Specialized.NameValueCollection;
if (address != null)
{
foreach (string key in address.AllKeys)
{
Response.Write(key + ": " + address[key] + "<br />");
}
}