你可以使用花括号来进行初始化,但这只适用于初始化时:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"},
{"s", "d"},
{"r", "m"}
};
这被称为 "集合初始化",适用于任何 ICollection<T>
(有关字典,请参见此链接;对于其他任何集合类型,请参见此链接)。实际上,它适用于实现了 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
方法:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
var anotherDictionary = new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
};
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"}
});