1

我想获取服务器地址值,但我收到了一个null reference exceptionin Alert 方法:

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; }
    }
}}
4

1 回答 1

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 />");
    }
}
于 2016-01-26T07:23:04.227 回答