Jam*_*uth 5 c# asp.net configuration
我正在编写一个类来描述config部分,并且正在寻找一种可能的方法来满足以下情况:
<plugins>
<add name="resize" maxheight="500px" maxwidth="500px"/>
<add name="watermark" font="arial"/>
</plugins>
Run Code Online (Sandbox Code Playgroud)
列表中的每个项目可以包含不同的属性以及必需的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;
}
}
Run Code Online (Sandbox Code Playgroud)
在你的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;
}
}
Run Code Online (Sandbox Code Playgroud)
Returning truefromOnDeserializeUnrecognizedAttribute表示您已经处理了无法识别的属性,并防止ConfigurationElement基类抛出异常,当您没有[ConfigurationProperty]在配置 xml 中为每个属性声明 a 时,它通常会抛出异常。
| 归档时间: |
|
| 查看次数: |
1553 次 |
| 最近记录: |