.NET Framework 添加到词典


Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "First");
dict.Add(2, "Second");

// To safely add items (check to ensure item does not already exist - would throw)
if(!dict.ContainsKey(3))
{
   dict.Add(3, "Third");
}

或者,可以通过索引器添加/设置它们。 (索引器内部看起来像一个属性,具有get和set,但是接受括号之间指定的任何类型的参数):

Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "First";
dict[2] = "Second";
dict[3] = "Third";

与抛出异常的Add方法不同,如果字符中已包含某个键,则索引器只是替换现有值。

对于线程安全字典,请使用ConcurrentDictionary<TKey, TValue>

var dict = new ConcurrentDictionary<int, string>();
dict.AddOrUpdate(1, "First", (oldKey, oldValue) => "First");