Dictionary.Item和Dictionary.Add有什么区别?

时间:2016-09-22 15:32:45

标签: c# dictionary

阅读C# Java HashMap equivalent的已接受答案,它的文学陈述:

  

C#的词典使用Item属性来设置/获取项目:

     
      
  • myDictionary.Item [key] = value
  •   
  • MyObject value = myDictionary.Item [key]
  •   

在尝试实现它时,使用时出现错误:

myDictionary.Item[SomeKey] = SomeValue;

  

错误:CS1061'字典'不包含的定义   '项目'

我需要使用myDictionary.Add(SomeKey, SomeValue);代替this answerMSDN - Dictionary来解决错误。

代码很好,但出于好奇,我做错了吗?除了一个不编译,

之间有什么区别
Dictionary.Item[SomeKey] = SomeValue; 

Dictionary.Add(SomeKey, SomeValue);

修改

我在C# Java HashMap equivalent编辑了接受的答案。请参阅版本历史以了解原因。

2 个答案:

答案 0 :(得分:2)

我认为区别在于:

    如果密钥不存在,
  • Dictionary[SomeKey] = SomeValue;(不是Dictionary.Item[SomeKey] = SomeValue;)将添加新的密钥值对,如果密钥存在,则会替换值
  • Dictionary.Add(SomeKey, SomeValue);将添加新的键值对,如果键已存在,则会抛出Argument Exception:已添加具有相同键的项目

示例是:

try
{
     IDictionary<int, string> dict = new Dictionary<int, string>();

     dict.Add(0, "a");
     dict[0] = "b";  // update value to b for the first key
     dict[1] = "c";  // add new key value pair
     dict.Add(0, "d"); // throw Argument Exception
 }
 catch (Exception ex)
 {
     MessageBox.Show(ex.Message);
 }

答案 1 :(得分:1)

差异很简单

Dictionary[SomeKey] = SomeValue; // if key exists already - update, otherwise add
Dictionary.Add(SomeKey, SomeValue); // if key exists already - throw exception, otherwise add

至于错误

Error: CS1061 'Dictionary' does not contain a definition for 'Item'

C#允许“默认”索引器,但它应该如何在内部实现?请记住,有许多语言使用CLR,而不仅仅是C#,他们还需要一种方法来调用该索引器。

CLR具有属性,并且它还允许在调用这些属性的getter或setter时提供参数,因为属性实际上是作为一对get_PropertyName()和set_PropertyName()方法编译的。因此,索引器可以由getter和setter接受其他参数的属性表示。

现在,没有名称的属性,所以我们需要为代表索引器的属性选择一个名称。默认情况下,“Item”属性用于indexer属性,但您可以使用IndexerNameAttribute覆盖它。

现在当indexer表示为常规命名属性时,任何CLR语言都可以使用get_Item(index)调用它。

这就是为什么在链接的文章中,Item引用了索引器。虽然当您从C#中使用它时,您必须使用适当的语法并将其称为

Dictionary[SomeKey] = SomeValue;