c# – 在config部分中创建动态keyvalue对
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在config部分中创建动态keyvalue对,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2318字,纯文字阅读大概需要4分钟。
内容图文
![c# – 在config部分中创建动态keyvalue对](/upload/InfoBanner/zyjiaocheng/784/db4a016df4f8433c83bf69cf9784246a.jpg)
我正在写一个类来描述一个配置部分,我正在寻找一种可能的方法来满足以下场景:
<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;
}
}
解决方法:
在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属性,并阻止ConfigurationElement基类抛出异常,当您没有为config xml中的每个属性声明[ConfigurationProperty]时,它通常会这样做.
内容总结
以上是互联网集市为您收集整理的c# – 在config部分中创建动态keyvalue对全部内容,希望文章能够帮你解决c# – 在config部分中创建动态keyvalue对所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。