2012-05-16 21 views
4

我正在寫一個類來描述一個配置部分,我在尋找一個可能的方法,以滿足以下情形:一個配置部分中創建動態鍵值對

<plugins> 
    <add name="resize" maxheight="500px" maxwidth="500px"/> 
    <add name="watermark" font="arial"/> 
</plugins> 

凡在每個項目列表可以包含不同的屬性以及所需的名稱屬性。設置默認部分很簡單,但我現在堅持如何添加動態鍵/值對。有任何想法嗎?

/// <summary> 
    /// Represents a PluginElementCollection collection configuration element 
    /// within the configuration. 
    /// </summary> 
    public class PluginElementCollection : ConfigurationElementCollection 
    { 
     /// <summary> 
     /// Represents a PluginConfig configuration element within the 
     /// configuration. 
     /// </summary> 
     public class PluginElement : ConfigurationElement 
     { 
      /// <summary> 
      /// Gets or sets the token of the plugin file. 
      /// </summary> 
      /// <value>The name of the plugin.</value> 
      [ConfigurationProperty("name", DefaultValue = "", IsRequired = true)] 
      public string Name 
      { 
       get { return (string)this["name"]; } 

       set { this["name"] = value; } 
      } 

      // TODO: What goes here to create a series of dynamic 
      // key/value pairs. 
     } 

     /// <summary> 
     /// Creates a new PluginConfig configuration element. 
     /// </summary> 
     /// <returns> 
     /// A new PluginConfig configuration element. 
     /// </returns> 
     protected override ConfigurationElement CreateNewElement() 
     { 
      return new PluginElement(); 
     } 

     /// <summary> 
     /// Gets the element key for a specified PluginElement 
     /// configuration element. 
     /// </summary> 
     /// <param name="element"> 
     /// The <see cref="T:System.Configuration.ConfigurationElement"/> 
     /// to return the key for. 
     /// </param> 
     /// <returns> 
     /// The element key for a specified PluginElement configuration element. 
     /// </returns> 
     protected override object GetElementKey(ConfigurationElement element) 
     { 
      return ((PluginElement)element).Name; 
     } 
    } 
+0

我已經回答了這個[這裏](http://stackoverflow.com/questions/2568454/code-required-to-use-foreach-on-my-own-custom-appsettings/2568780#2568780)。請注意,您可能需要將SystemConfiguguration替換爲System.Configuration,因爲我使用'using'別名來解決命名衝突。 –

+0

@Morten Mertner - 看看你的代碼,它似乎只處理一個默認情況,你事先知道鍵/值。我希望能夠爲每個實例添加自定義對。 –

+0

不,代碼是用於包含元素列表的完全自定義配置節。你可能顯然需要修改一些位,因爲你想存儲不同的值,但所需的類都在那裏。 –

回答

3

在你ConfigurationElement您可以覆蓋OnDeserializeUnrecognizedAttribute(),然後存儲額外的屬性某處,在字典例如:

public class PluginElement : ConfigurationElement 
{ 
    public IDictionary<string, string> Attributes { get; private set; } 

    public PluginElement() 
    { 
     Attributes = new Dictionary<string, string>(); 
    } 

    protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) 
    { 
     Attributes.Add(name, value); 
     return true; 
    } 
} 

OnDeserializeUnrecognizedAttribute返回true表明您已經處理了unrecongnized屬性,可以防止基類拋出異常,如果您尚未爲config xml中的每個屬性聲明[ConfigurationProperty],則通常會執行此異常。

+0

感謝你。我會放棄並報告。 –