16

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

通常,您有一个继承自 的类,ConfigurationSection然后该类具有继承自 的类型的属性,ConfigurationElementCollection然后返回从 继承的类型的集合的元素ConfigurationElement。要配置它,您将需要如下所示的 XML:

<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>
4

1 回答 1

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>
于 2013-01-17T22:05:59.737 回答