您可以为此使用花括号,但这仅适用于初始化:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"},
{"s", "d"},
{"r", "m"}
};
这称为“集合初始化”,适用于任何ICollection<T>(请参阅link 用于字典或此link 用于任何其他集合类型)。事实上,它适用于任何实现了IEnumerable 并包含Add 方法的对象类型:
class Foo : IEnumerable
{
public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { }
// ...
}
Foo foo = new Foo
{
{1, 2, 3},
{2, 3, 4}
};
基本上,这只是重复调用Add-方法的语法糖。初始化后有几种方法可以做到这一点,其中一种是手动调用Add-methods:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
var anotherDictionary = new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
};
// Merge anotherDictionary into myDictionary, which may throw
// (as usually) on duplicate keys
foreach (var keyValuePair in anotherDictionary)
{
myDictionary.Add(keyValuePair.Key, keyValuePair.Value);
}
或者作为扩展方法:
static class DictionaryExtensions
{
public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source)
{
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
foreach (var keyValuePair in source)
{
target.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
myDictionary.Add(new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
});