【发布时间】:2012-07-19 09:04:47
【问题描述】:
Dictionary.Add 方法和索引器Dictionary[key] = value 有什么区别?
【问题讨论】:
-
我来寻找是因为我担心旧版本的 C# 可能需要使用 .Add() 来添加元素,但显然不需要。
Dictionary.Add 方法和索引器Dictionary[key] = value 有什么区别?
【问题讨论】:
添加 -> 如果字典中已存在项,则将项添加到字典中,将引发异常。
索引器或Dictionary[Key] => 添加或更新。如果字典中不存在该键,则将添加一个新项。如果键存在,则值将使用新值更新。
dictionary.add 将向字典中添加一个新项目,dictionary[key]=value 将为字典中的现有条目设置一个值,以针对一个键。如果键不存在,则 (indexer) 将在字典中添加该项目。
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("Test", "Value1");
dict["OtherKey"] = "Value2"; //Adds a new element in dictionary
Console.Write(dict["OtherKey"]);
dict["OtherKey"] = "New Value"; // Modify the value of existing element to new value
Console.Write(dict["OtherKey"]);
在上面的例子中,首先dict["OtherKey"] = "Value2"; 将在字典中添加一个新值,因为它不存在,其次它会将值修改为新值。
【讨论】:
dictionar[key]=value中不存在时?
Dictionary.Add 如果密钥已经存在则抛出异常。 [] 用于设置项目时不会(如果您尝试访问它以进行读取,则会这样做)。
x.Add(key, value); // will throw if key already exists or key is null
x[key] = value; // will throw only if key is null
var y = x[key]; // will throw if key doesn't exists or key is null
【讨论】:
当键在字典中不存在时的行为是相同的:在这两种情况下都会添加该项目。
当密钥已经存在时,行为会有所不同。 dictionary[key] = value 将更新映射到键的值,而 dictionary.Add(key, value) 将改为抛出 ArgumentException。
【讨论】:
dictionary.add 将项目添加到字典中,而 dictionary[key]=value 将值分配给已经存在的键。
【讨论】:
dictionary[key]=value 如果键不存在,则添加键和值。所以它是一种添加或更新方式