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.
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)
当字典中不存在键时,行为是相同的:在这两种情况下都将添加该项目。
当密钥已经存在时,行为会有所不同。 dictionary[key] = value
将更新映射到键的值,而dictionary.Add(key, value)
将抛出 ArgumentException。