【发布时间】:2016-05-02 16:58:39
【问题描述】:
我想获取服务器地址值,但我在 Alert 方法中收到了null reference exception:
Values.Server.Key["CollectorServer"].Address -> 空引用 异常
我的 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; }
}
}}
【问题讨论】:
-
看看this thread,或许对你有帮助
-
如果您所做的只是添加键/值设置类型,那么只需使用 appsettings 配置部分
标签: c# nullreferenceexception configsection