【问题标题】:How do I make my custom config section behave like a collection?如何使我的自定义配置部分表现得像一个集合?
【发布时间】:2013-01-01 13:11:51
【问题描述】:

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

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

<customSection>
  <collection>
    <element name="A" />
    <element name="B" />
    <element name="C" />
  </collection>
</customSection>

我想删掉&lt;collection&gt; 节点,然后:

<customSection>
  <element name="A" />
  <element name="B" />
  <element name="C" />
<customSection>

【问题讨论】:

  • 您能否考虑将问题的标题更改为更具体?我建议类似“如何使我的自定义配置部分表现得像一个集合?”或类似的规定。这会自动从问题标题中删除“C#”,这是不必要的,因为您已经用它标记了问题。
  • 当您提出实际问题时,您很快就会意识到很可能有人已经问过了。例如,This one 可能与您的问题重复。

标签: c# custom-configuration


【解决方案1】:

我假设 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>

【讨论】:

  • 您的示例中有三个类。我知道这是 Microsoft 向我们展示的方法……但这意味着您的 XML 将具有三个级别:部分、集合、集合中的元素。我想用两个来做:节,节中的元素(好像节也是一个集合)。
  • @theBoringCoder 您的类中确实还有三个级别,但是这个示例使用的正是您想要的示例。 MyElementCollection 类不会转换为 xml 元素。
  • 啊啊啊……好吧。感谢您的回答。
  • @theBoringCoder 哇,回复有点延迟 :)
猜你喜欢
  • 2013-10-31
  • 2011-11-04
  • 2011-09-16
  • 2011-08-05
  • 1970-01-01
  • 2012-11-04
  • 2012-03-24
  • 1970-01-01
  • 2010-10-25
相关资源
最近更新 更多