Dictionary.Add vs Dictionary [key] = value的区别

rsg*_*rsg 73 .net c#

Dictionary.Add方法和索引器之间有什么区别Dictionary[key] = value

Hab*_*bib 116

添加 - >如果项目已存在于字典中,则会向字典添加项目,将引发异常.

索引器或Dictionary[Key]=> 添加或更新.如果字典中不存在该键,则将添加新项.如果密钥存在,则将使用新值更新该值.


dictionary.add将向字典添加新项目,dictionary[key]=value将针对键设置字典中现有条目的值.如果密钥不存在,那么它(索引器)将在字典中添加该项.

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"]);
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,首先dict["OtherKey"] = "Value2";将在字典中添加一个新值,因为它不存在,在第二个位置它将值修改为New Value.

  • @rsg,对于添加一个新项目,dictionary.add 是更好的选择,因为它会让你知道字典中是否已经存在键,使用字典 [key],如果键存在就会更新它,否则它会添加一个新的 (2认同)

xan*_*tos 30

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
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 17

这个文档Add非常清楚,我觉得:

您还可以使用该Item属性通过设置不存在的键的值来添加新元素Dictionary(Of TKey, TValue); 例如,myCollection[myKey] = myValue(在Visual Basic中myCollection(myKey) = myValue).但是,如果指定的键已存在,则Dictionary(Of TKey, TValue)设置Item属性将覆盖旧值.相反,Add如果已存在具有指定键的值,则该方法将引发异常.

(请注意,该Item属性对应于索引器.)

在提出问题之前,总是值得查阅文档...


cdh*_*wie 6

当字典中不存在键时,行为是相同的:在这两种情况下都将添加该项目。

当密钥已经存在时,行为会有所不同。 dictionary[key] = value将更新映射到键的值,而dictionary.Add(key, value)将抛出 ArgumentException。