在配置节中创建动态键值对

时间:2012-05-16 12:31:54

标签: c# asp.net configuration

我正在编写一个类来描述一个配置部分,我正在寻找一种可能的方法来满足以下场景:

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

列表中的每个项目都可以包含不同的属性以及所需的name属性。设置默认部分很简单,但我现在不知道如何添加动态键/值对。有什么想法吗?

    /// <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;
        }
    }

1 个答案:

答案 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;
    }
}

true返回OnDeserializeUnrecognizedAttribute表示您已经处理了未记录的属性,并阻止ConfigurationElement基类抛出异常,通常在您退出时执行异常&# 39; t为config xml中的每个属性声明[ConfigurationProperty]