.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 好听的元旦简短祝福语