the*_*der 16 c# custom-configuration
我如何编写自定义,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>
Eli*_*ing 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>