你不应该使用NameValueCollection
. 它的性能很差,并且会连接重复键的值。
您可以使用KeyValuePair
´s 并为此创建自己的处理程序:
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");