Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Dictionary.Add与Dictionary[key]=值的差异_C#_.net - Fatal编程技术网

C# Dictionary.Add与Dictionary[key]=值的差异

C# Dictionary.Add与Dictionary[key]=值的差异,c#,.net,C#,.net,Dictionary.Add方法和索引器Dictionary[key]=value之间有什么区别 Add->将项添加到字典中如果字典中已存在项,将引发异常 索引器或字典[键]=>添加或更新。如果字典中不存在该键,将添加一个新项。如果该键存在,则该值将用新值更新 dictionary.add将向字典中添加一个新项,dictionary[key]=value将根据键为字典中的现有条目设置一个值。如果该键不存在,则它(索引器)将在字典中添加该项 Dictionary<string, strin

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

Add->将项添加到字典中如果字典中已存在项,将引发异常

索引器或
字典[键]
=>添加或更新。如果字典中不存在该键,将添加一个新项。如果该键存在,则该值将用新值更新



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"]);
Dictionary dict=new Dictionary();
添加(“测试”、“值1”);
dict[“OtherKey”]=“Value2”//在字典中添加新元素
Console.Write(dict[“OtherKey”]);
dict[“OtherKey”]=“新值”//将现有图元的值修改为新值
Console.Write(dict[“OtherKey”]);

在上面的示例中,首先
dict[“OtherKey”]=“Value2”
将在字典中添加一个新值,因为它不存在,其次它将把该值修改为新值

dictionary.add
将项添加到字典,而
dictionary[key]=value
将值分配给已存在的键。

dictionary.add
如果键已存在,则会引发异常<代码>[]当用于设置项目时,不会(如果您尝试访问该项目以进行读取,则会)


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

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

的文档非常清楚,我觉得:

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


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

并且当该键不存在于
字典[key]=value
?@HenkHolterman中时,它将使用新的keyThaks Habib添加到字典中。但是我们可以使用dictionars[newkey]=value添加新键。哪一个更好?@rsg,对于添加新项,dictionary.add是更好的选择,因为它会让您知道字典中是否已经存在密钥,使用dictionary[key],如果密钥存在,将更新它,否则,它将添加一个新的参数。如果使用add方法时键已存在,则将引发ArgumentException。
dictionary[key]=value
添加键,如果键不存在,则添加值。因此,这是一种添加或更新的方式,因为我担心旧版本的C#可能需要使用.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