public class ComplexSection : ConfigurationSection
{
[ConfigurationProperty("height", IsRequired = true)]
public int Height
{
get
{
return (int)base["height"];
}
set
{
base["height"] = value;
}
}
[ConfigurationProperty("child", IsDefaultCollection = false)]
public ChildSection Child
{
get
{
return (ChildSection)base["child"];
}
set
{
base["child"] = value;
}
}
}
public class ChildSection : ConfigurationElement
{
[ConfigurationProperty("firstName", IsRequired = true, IsKey = true)]
public string FirstName
{
get
{
return (string)base["firstName"];
}
set
{
base["firstName"] = value;
}
}
[ConfigurationProperty("lastName", IsRequired = true)]
public string LastName
{
get
{
return (string)base["lastName"];
}
set
{
base["lastName"] = value;
}
}
}
还有稍微再复杂一点的情况,我们可能要在配置中配置一组相同类型的节点,也就是一组节点的集合。如下面的配置:
复制代码 代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section type="ConfigExample.Configuration.ComplexSection,ConfigExample"/>
</configSections>
<complex>
<child firstName="James" lastName="Bond"/>
<children>
<add firstName="Zhao" lastName="yukai"/>
<add firstName="Lee" lastName="yukai"/>
<remove firstName="Zhao"/>
</children>
</complex>
</configuration>
请看children节点,它就是一个集合类,在它里面定义了一组add元素,也可以有remove节点把已经添进去的配置去掉。
要使用自定义节点集合需要从ConfigurationElementCollection类继承一个自定义类,然后要实现此类GetElementKey(ConfigurationElement element)和ConfigurationElement CreateNewElement()两个方法;为了方便的访问子节点可以在这个类里面定义只读的索引器。请看下面的实现
复制代码 代码如下:
public class Children : ConfigurationElementCollection
{
protected override object GetElementKey(ConfigurationElement element)
{
return ((ChildSection)element).FirstName;
}
protected override ConfigurationElement CreateNewElement()
{
return new ChildSection();
}
public ChildSection this[int i]
{
get
{
return (ChildSection)base.BaseGet(i);
}
}
public ChildSection this[string key]
{
get
{
return (ChildSection)base.BaseGet(key);
}
}
}
当然要使用此集合类我们必须在Complex类中添加一个此集合类的属性,并要指定集合类的元素类型等属性,如下:
复制代码 代码如下: