.NET Framework 添加到字典
示例
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "First");
dict.Add(2, "Second");
//为了安全地添加项目(检查以确保该项目尚不存在-会抛出)
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");
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短