Difference of Dictionary.Add vs Dictionary[key]=value
添加->向字典添加项如果字典中已存在项,则将引发异常。
indexer或
1 2 3 4 5 6 | 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"]); |
在上面的示例中,首先,
如果密钥已经存在,
1 2 3 | 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 |
号
You can also use the
Item property to add new elements by setting the value of a key that does not exist in theDictionary(Of TKey, TValue) ; for example,myCollection[myKey] = myValue (in Visual Basic,myCollection(myKey) = myValue ). However, if the specified key already exists in theDictionary(Of TKey, TValue) , setting the Item property overwrites the old value. In contrast, theAdd method throws an exception if a value with the specified key already exists.
号
(注意,
在问问题之前,一定要查阅文档…
当字典中不存在键时,行为是相同的:两种情况下都将添加该项。
当键已经存在时,行为会有所不同。