C# 如何创建包含集合的配置节

C# 如何创建包含集合的配置节,c#,.net,configuration,system.configuration,C#,.net,Configuration,System.configuration,这里有一个很好的问题和答案,说明了如何创建一个自定义配置节,该节能够将以下表单的配置解析为.Net对象: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="CustomConfigSection" type="ConfigTest.CustomConfigSection,ConfigTest" /> <

这里有一个很好的问题和答案,说明了如何创建一个自定义配置节,该节能够将以下表单的配置解析为.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>

我遇到的问题是,类型
CustomConfigSection
似乎需要从和继承,这在C#中当然是不可能的。我发现的另一种方法需要我来实现,这在.NETV2中已被弃用。有人知道如何达到预期的结果吗?谢谢。

您不需要同时从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"];
        }
    }   
}
public class MyConfigElement: ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get
        {
            return (string)base["key"];
        }
    }   
}