自定义配置节注意事项

1、属性大小写问题

比如有这样一个配置节,其中有三个属性name,ip,port
  <Server name="server1" ip="192.168.0.11" port="80" />

那么对应的类要跟这个名字完全匹配,包括大小写。

public class Server : ConfigurationElement
{
    [ConfigurationProperty("name", DefaultValue = "Server1", IsRequired = true, IsKey = true)]
    public string Name {get;set;}
   

    [ConfigurationProperty("ip", DefaultValue = "127.0.0.1", IsRequired = true, IsKey = false)]
    public string IP {get;set;}

    [ConfigurationProperty("port", DefaultValue = "80", IsRequired = true, IsKey = false)]
    public int Port {get;set;}

}


 

2、配置节名称(也是一个大小写问题)

这样一个配置节

<ServerList>
  <server name="server1" ip="192.168.0.11" port="80" />
  <server name="server2" ip="192.168.0.12" port="80" />
</ServerList>

public class ServerCollection : ConfigurationElementCollection
{

    … …

    protected override string ElementName
    {
        get { return "server"; }
    }

}

3、section的名称要对应

<configSections>
  <section name="serverList" type="Aricc.Engine.Client.Config.ServerList,Aricc.Engine.Client" />
</configSections>
<serverList>
  <server name="server1" ip="192.168.0.11" port="80" />
  <server name="server2" ip="192.168.0.12" port="80" />
</serverList>

对应后台代码

Config.ServerList configList = (Config.ServerList)ConfigurationManager.GetSection("serverList") as Config.ServerList;

对应的配置节类的名称可以不一样

public class ServerList : ConfigurationSection{}

你可能感兴趣的:(自定义)