如何使我的自定义配置部分的行为像集合? [英] How do I make my custom config section behave like a collection?
问题描述
我该如何编写我的自定义ConfigurationSection
,使其既是节处理程序又是配置元素集合?
How would I need to write my custom ConfigurationSection
so that it is both a section handler and a configuration element collection?
通常,您有一个从ConfigurationSection
继承的类,然后该类具有从ConfigurationElementCollection
继承的类型的属性,该属性然后返回从ConfigurationElement
继承的类型的集合的元素.要配置它,您将需要看起来像这样的XML:
Normally, you have one class that inherits from ConfigurationSection
, which then has a property that is of a type that inherits from ConfigurationElementCollection
, which then returns elements of a collection of a type that inherits from ConfigurationElement
. To configure that, you would then need XML that looks something like this:
<customSection>
<collection>
<element name="A" />
<element name="B" />
<element name="C" />
</collection>
</customSection>
我想剪掉<collection>
节点,只是:
<customSection>
<element name="A" />
<element name="B" />
<element name="C" />
<customSection>
推荐答案
我假定collection
是自定义ConfigurationSection
类的属性.
I assume that the collection
is a property of your custom ConfigurationSection
class.
您可以使用以下属性装饰此属性:
You can decorate this property with the following attributes:
[ConfigurationProperty("", IsDefaultCollection = true)]
[ConfigurationCollection(typeof(MyElementCollection), AddItemName = "element")]
您的示例的完整实现如下所示:
A full implementation for your example could look like this:
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"]; }
}
}
现在您可以像这样访问您的设置:
Now you can access your settings like this:
var config = (MyCustomSection)ConfigurationManager.GetSection("customSection");
foreach (MyElement el in config.Elements)
{
Console.WriteLine(el.Name);
}
这将允许以下配置部分:
This will allow the following configuration section:
<customSection>
<element name="A" />
<element name="B" />
<element name="C" />
<customSection>
这篇关于如何使我的自定义配置部分的行为像集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!