16

ConfigurationSectionセクションハンドラーと構成要素コレクションの両方になるように、カスタムをどのように作成する必要がありますか?

通常、から継承するクラスが1つあり、そのクラスには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 に答える