2015-06-01 135 views
4

配置節有一個很大的問題,並回答here,說明如何創建自定義配置部分,它能夠解析以下形式的配置爲.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類型需要來自兩個ConfigurationSectionConfigurationElementCollection,繼承的問題,它的當然在C#中是不可能的。我發現的另一種方法要求我實施IConfigurationSectionHandler,它已從.Net v2棄用。有誰知道如何完成預期的結果?謝謝。

回答

8

您不需要從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"]; 
     } 
    } 
} 
相關問題