創建擴展方法最有可能你會希望使用其再次這樣可以防止重複的代碼。
實現:
public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
{
if (collection == null)
{
throw new ArgumentNullException("Collection is null");
}
foreach (var item in collection)
{
if(!source.ContainsKey(item.Key)){
source.Add(item.Key, item.Value);
}
else
{
// handle duplicate key issue here
}
}
}
用法:
Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();
animals.AddRange(newanimals);
沒問題。重複密鑰不是一個擔心。 – xbonez 2010-10-20 21:42:26
我建議你看看我的解決方案並實現'AddRange'。我爲你做了所有的工作。 – Gabe 2010-10-20 21:46:42
@gmcalab:我很欣賞它,但是這個解決方案對我來說工作得很好,而且體積更小。我真的在尋找一些能夠完成這項工作的小東西。 – xbonez 2010-10-21 12:07:30