.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 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短