自定义配置节示例(.NET 2.0)

在2.0中已经不建议使用 IConfigurationSectionHandler 接口来实现自定义配置节,而是改用创建 ConfigurationSection 的派生类来创建自定义配置节。

现在我希望的配置文件的结构如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<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>
</configuration>

原来接口的方式好像比较容易实现相应类的编写。但是到了2.0,嗯,从Google上找了一个晚上也没有找到相关的例子。大多的是可以实现这样的结构

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

可是我又比较。。。怎么说呢。反正就是想实现之前的样子。找了好多人的帖子就是没有类似的。怎么办,豁出去了,加载我多年不用的英文单词到大脑,试试看吧。

找啊找啊找代码。。。。

哈哈

找到一个好代码。

找到的代码太长的,我就不贴了。

我把我学来的东西,帖出来与大家分享。

代码如下,已经过测试。

代码
/// <summary>
/// 自定义配置节类
/// 客户端可连接的服务器列表
/// </summary>
public class ServerList : ConfigurationSection
{
/// <summary>
/// 服务器列表
/// </summary>
[ConfigurationProperty("", IsDefaultCollection = true)]
public ServerCollection Items
{
get { return (ServerCollection)base[""]; }
}
}

/// <summary>
/// 服务器配置节类
/// 对应一项服务器配置
/// </summary>
public class Server : ConfigurationElement
{
/// <summary>
/// 服务器名称
/// </summary>
[ConfigurationProperty("name", DefaultValue = "Server1", IsRequired = true, IsKey = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}

/// <summary>
/// 服务器IP
/// </summary>
[ConfigurationProperty("ip", DefaultValue = "127.0.0.1", IsRequired = true, IsKey = false)]
public string IP
{
get
{
return (string)this["ip"];
}
set
{
this["ip"] = value;
}
}

/// <summary>
/// 服务器端口
/// </summary>
[ConfigurationProperty("port", DefaultValue = "80", IsRequired = true, IsKey = false)]
public int Port
{
get
{
return (int)this["port"];
}
set
{
this["port"] = value;
}
}
}

/// <summary>
/// 服务器配置集合
/// </summary>
public class ServerCollection : ConfigurationElementCollection
{
public new Server this[string name]
{
get
{
if (IndexOf(name) < 0) return null;
return (Server)BaseGet(name);
}
}
public Server this[int index]
{
get { return (Server)BaseGet(index); }
}

public int IndexOf(string name)
{
name
= name.ToLower();
for (int idx = 0; idx < base.Count; idx++)
{
if (this[idx].Name.ToLower() == name)
return idx;
}
return -1;
}

public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}

protected override ConfigurationElement CreateNewElement()
{
return new Server();
}

protected override object GetElementKey(ConfigurationElement element)
{
return ((Server)element).Name;
}

/// <summary>
/// 集合内元素的名称
/// </summary>
protected override string ElementName
{
get { return "server"; }
}

}
原文地址:https://www.cnblogs.com/Aricc/p/1660439.html