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

时间:2012-07-19 09:04:47

标签: c# .net

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

5 个答案:

答案 0 :(得分:97)

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

Indexer或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"]);

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

答案 1 :(得分:29)

如果密钥已存在,则

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

答案 2 :(得分:16)

Add的文档非常明确,我觉得:

  

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

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

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

答案 3 :(得分:2)

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

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

答案 4 :(得分:1)

dictionary.add将一个项目添加到字典中,而dictionary[key]=value将一个值分配给已存在的密钥。

相关问题