我需要添加鍵/對象對字典,但我當然需要先檢查密鑰是否已經存在,否則我得到一個「密鑰已存在於字典」錯誤。下面的代碼解決了這個問題,但是笨重。有沒有更安全的將項目添加到Dictionary <>的方法?
什麼是更好的方式做到這一點,而不是像這樣的字符串幫助器方法?
using System;
using System.Collections.Generic;
namespace TestDictStringObject
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> currentViews = new Dictionary<string, object>();
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2");
StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1");
StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1");
foreach (KeyValuePair<string, object> pair in currentViews)
{
Console.WriteLine("{0} {1}", pair.Key, pair.Value);
}
Console.ReadLine();
}
}
public static class StringHelpers
{
public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, view);
}
else
{
dict[key] = view;
}
}
}
}
優秀,沒想到簡單的分配採取了加照顧/覆蓋問題,很好。 – 2009-07-24 13:17:12