可以使用大括號的是,雖然這只是初始化工作:
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
- 方法:
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"}
});
http://msdn.microsoft.com/en-us/library/bb531208.aspx – Marc
[在C#中合併字典]的可能重複(http://stackoverflow.com/questions/294138/merging-dictionaries-in -c-sharp) –