我假设这collection
是您的自定义ConfigurationSection
类的属性。
您可以使用以下属性装饰此属性:
[ConfigurationProperty("", IsDefaultCollection = true)]
[ConfigurationCollection(typeof(MyElementCollection), AddItemName = "element")]
您的示例的完整实现可能如下所示:
public class MyCustomSection : ConfigurationSection
{
[ConfigurationProperty("", IsDefaultCollection = true)]
[ConfigurationCollection(typeof(MyElementCollection), AddItemName = "element")]
public MyElementCollection Elements
{
get { return (MyElementCollection)this[""]; }
}
}
public class MyElementCollection : ConfigurationElementCollection, IEnumerable<MyElement>
{
private readonly List<MyElement> elements;
public MyElementCollection()
{
this.elements = new List<MyElement>();
}
protected override ConfigurationElement CreateNewElement()
{
var element = new MyElement();
this.elements.Add(element);
return element;
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MyElement)element).Name;
}
public new IEnumerator<MyElement> GetEnumerator()
{
return this.elements.GetEnumerator();
}
}
public class MyElement : ConfigurationElement
{
[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
}
}
现在您可以像这样访问您的设置:
var config = (MyCustomSection)ConfigurationManager.GetSection("customSection");
foreach (MyElement el in config.Elements)
{
Console.WriteLine(el.Name);
}
这将允许以下配置部分:
<customSection>
<element name="A" />
<element name="B" />
<element name="C" />
<customSection>