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

the*_*der 16 c# custom-configuration

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

通常,您有一个继承自的类,该类具有继承自ConfigurationSection的类型的属性,ConfigurationElementCollection然后返回继承自的类型的集合的元素ConfigurationElement.要配置它,您需要看起来像这样的XML:

<customSection>
  <collection>
    <element name="A" />
    <element name="B" />
    <element name="C" />
  </collection>
</customSection>
Run Code Online (Sandbox Code Playgroud)

我想删除<collection>节点,只需:

<customSection>
  <element name="A" />
  <element name="B" />
  <element name="C" />
<customSection>
Run Code Online (Sandbox Code Playgroud)

Eli*_*ing 24

我假设它collection是您的自定义ConfigurationSection类的属性.

您可以使用以下属性装饰此属性:

[ConfigurationProperty("", IsDefaultCollection = true)]
[ConfigurationCollection(typeof(MyElementCollection), AddItemName = "element")]
Run Code Online (Sandbox Code Playgroud)

您的示例的完整实现可能如下所示:

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"]; }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样访问您的设置:

var config = (MyCustomSection)ConfigurationManager.GetSection("customSection");

foreach (MyElement el in config.Elements)
{
    Console.WriteLine(el.Name);
}
Run Code Online (Sandbox Code Playgroud)

这将允许以下配置部分:

<customSection>
    <element name="A" />
    <element name="B" />
    <element name="C" />
<customSection>
Run Code Online (Sandbox Code Playgroud)

  • @theBoringCoder你的类中确实还有三个级别,但是这个例子恰好使用了你想要的例子.`MyElementCollection`类不会转换为xml元素. (3认同)
  • @theBoringCoder哇,这是一些延迟回应:) (3认同)