Как создать раздел конфигурации, содержащий коллекцию

Здесь есть большой вопрос и ответ, который иллюстрирует, как создать пользовательский раздел конфигурации, способный анализировать конфигурацию следующей формы в объектах.Net:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="CustomConfigSection" type="ConfigTest.CustomConfigSection,ConfigTest" />
  </configSections>

  <CustomConfigSection>
    <ConfigElements>
      <ConfigElement key="Test1" />
      <ConfigElement key="Test2" />
    </ConfigElements>
  </CustomConfigSection>

</configuration>

Мой вопрос, кто-нибудь знает, как создать тот же пользовательский раздел конфигурации без ConfigElements элемент? Например, тот, который будет анализировать следующее CustomConfigSection элемент вместо показанного выше:

  <CustomConfigSection>
    <ConfigElement key="Test1" />
    <ConfigElement key="Test2" />
  </CustomConfigSection>

Проблема, которая у меня есть, заключается в том, что кажется, что тип CustomConfigSection должен наследоваться как от ConfigurationSection, так и от ConfigurationElementCollection, что, конечно, невозможно в C#. Другой подход, который я нашел, требует, чтобы я реализовал IConfigurationSectionHandler, который не рекомендуется для.Net v2. Кто-нибудь знает, как добиться желаемого результата? Благодарю.

1 ответ

Решение

Вам не нужно наследовать от ConfigurationSection и ConfigurationElementCollection. Вместо этого определите раздел конфигурации следующим образом:

public class CustomConfigSection : ConfigurationSection
{
    [ConfigurationProperty("", IsDefaultCollection = true)]
    public MyConfigElementCollection ConfigElementCollection
    {
        get
        {
            return (MyConfigElementCollection)base[""];
        }
    }
}

И ваша коллекция элементов конфигурации:

[ConfigurationCollection(typeof(MyConfigElement), AddItemName = "ConfigElement"]
public class MyConfigElementCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new MyConfigElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        return ((MyConfigElement)element).key;
    }
}

И сам элемент конфигурации:

public class MyConfigElement: ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get
        {
            return (string)base["key"];
        }
    }   
}
Другие вопросы по тегам