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

Get multiple instances of the same key within custom section

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

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

我正在使用以下代码从阅读条目中获取 NameValueCollection object。

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

我希望此代码 return 该部分下的每个条目,但它似乎只返回与键相关的唯一值。我怎样才能收集 <section1> 的所有 children 而不管密钥?

你不应该使用 NameValueCollection。它有 bad performance and concatenates values 个重复键。

您可以使用 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");

根据定义,键必须是唯一的。

"I have to store mail recipients in the app.config. Each section has it's own list of MailTo and CC entries and the section name dictates which group to send the mail out to."

那你就没有一堆key/mail对了。

你有一堆 key/mail[] 对。

对于每个键,您都有一个值集合。所以你使用了一个值的集合。答案是这样的:

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