在自定义部分中获取同一密钥的多个实例



在我的app.config文件中,我在configuration下有一个自定义部分,其中包含共享同一键的多个条目。

<setion1>
<add key="key1" value="value1"/>
<add key="key2" value="value2"/>
<add key="key1" value="value3"/>
</section1>

我使用以下代码从读取条目中获取NameValueCollection对象。

var list = (NameValueCollection)ConfigurationManager.GetSection("section1");

我希望这段代码返回该部分下的每个条目,但它似乎只带回与键有关的唯一值。如何收集<section1>的所有子项,而不考虑钥匙?

键必须根据定义是unqiue。

"我必须在 app.config 中存储邮件收件人。每个部分都有自己的 MailTo 和 CC 条目列表,部分名称指示将邮件发送到哪个组。

那么你没有一堆密钥/邮件对。

你有一堆密钥/邮件[]对。

对于每个键,您都有一个值集合。因此,您使用值的集合。答案是这样的:https://stackoverflow.com/a/1779453/3346583

当然,在这种情况下,可扩展性可能是一个问题。但是,如果您需要可伸缩性,那么无论如何,您都应该将其作为数据库/XML 文件/其他数据结构中的 1:N 关系来解决。而不是app.onfig条目。

你不应该使用NameValueCollection.它的性能很差,并连接重复键的值。

您可以使用KeyValuePair的并为此创建自己的处理程序:

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Xml;
using KeyValue = System.Collections.Generic.KeyValuePair<string, string>;
namespace YourNamespace
{
public sealed class KeyValueHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
var result = new List<KeyValue>();
foreach (XmlNode child in section.ChildNodes)
{
var key = child.Attributes["key"].Value;
var value = child.Attributes["value"].Value;
result.Add(new KeyValue(key, value));
}
return result;
}
}
}

配置:

<configSections>
<section name="section1" type="YourNamespace.KeyValueHandler, YourAssembly" />
</configSections>
<setion1>
<add key="key1" value="value1"/>
<add key="key2" value="value2"/>
<add key="key1" value="value3"/>
</section1>

用法:

var list = (IList<KeyValue>)ConfigurationManager.GetSection("section1");

最新更新