如何使我的自定义配置部分表现得像一个集合?

时间:2013-01-17 21:33:48

标签: c# custom-configuration

我如何编写自定义ConfigurationSection以便它既是部分处理程序又是配置元素集合?

通常,您有一个继承自ConfigurationSection的类,该类具有继承自ConfigurationElementCollection的类型的属性,然后返回继承自的ConfigurationElement类型的集合的元素。 <customSection> <collection> <element name="A" /> <element name="B" /> <element name="C" /> </collection> </customSection> 。要配置它,您需要看起来像这样的XML:

<collection>

我想删除<customSection> <element name="A" /> <element name="B" /> <element name="C" /> <customSection> 节点,只需:

{{1}}

1 个答案:

答案 0 :(得分:24)

我认为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>