Dictionary.Add与Dictionary [key] = value的差异 [英] Difference of Dictionary.Add vs Dictionary[key]=value

查看:40
本文介绍了Dictionary.Add与Dictionary [key] = value的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the difference between the Dictionary.Add method and the indexer Dictionary[key] = value?

推荐答案

添加->如果字典中已存在该项,则将其添加到字典中.

Add -> Adds an item to the dictionary if item already exists in the dictionary an exception will be thrown.

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

Indexer or Dictionary[Key] => Add Or Update. If the key doesn't exist in the dictionary, a new item will be added. If the key exists then the value will be updated with the new value.

dictionary.add 将向字典中添加一个新项目, dictionary [key] = value 将针对键为字典中的现有条目设置一个值.如果键不存在,则它(indexer)将该项添加到字典中.

dictionary.add will add a new item to the dictionary, dictionary[key]=value will set a value to an existing entry in the dictionary against a key. If the key is not present then it (indexer) will add the item in the dictionary.

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"; 将在字典中添加新值,因为它不存在,而第二位将将该值修改为新值".

In the above example, in first place dict["OtherKey"] = "Value2"; will add a new value in the dictionary because it doesn't exist, and in second place it will modify the value to New Value.

这篇关于Dictionary.Add与Dictionary [key] = value的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆