2016-09-22 22 views
2

讀的C# Java HashMap equivalent接受的答案,它的文學狀態:Dictionary.Item和Dictionary.Add有什麼區別?

C#'s Dictionary uses the Item property for setting/getting items:

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

,並試圖實現它的時候,使用的時候,我得到了一個錯誤:

myDictionary.Item[SomeKey] = SomeValue;

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

我需要使用myDictionary.Add(SomeKey, SomeValue);而不是this answerMSDN - Dictionary來解決錯誤。

代碼是好的,但出於好奇我是否做錯了什麼?除了一個沒有編制,是什麼

Dictionary.Item[SomeKey] = SomeValue; 

Dictionary.Add(SomeKey, SomeValue); 

之間的區別編輯:

我編輯接受的答案在C# Java HashMap equivalent。查看版本歷史知道原因。

+4

如果字典中已經包含SomeKey,而前者不會,則後者將拋出DuplicateKeyException。把它看作AddOrUpdate。 –

+0

This first:Dictionary.Item [SomeKey] = SomeValue;是要更改字典中已有的值。另一種是將新項目添加到字典中。 – jdweng

+3

至於你的錯誤,只是省略Item,像這樣:myDictionary [SomeKey] = SomeValue; – Evk

回答

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具有屬性,並且它還允許在調用那些屬性獲取器或設置器時提供參數,因爲屬性實際上編譯爲一對get_PropertyName()和set_PropertyName()方法。因此,索引器可以由getter和setter接受附加參數的屬性表示。

現在,不能有沒有名稱的財產,所以我們需要爲代表我們的索引器的財產選擇一個名稱。默認情況下,「Item」屬性用於索引器屬性,但您可以用IndexerNameAttribute覆蓋它。

現在,當索引器被表示爲常規命名屬性時,任何CLR語言都可以使用get_Item(index)來調用它。

這就是爲什麼在您鏈接的文章中,索引器被Item引用。雖然從C#使用它時,必須使用恰當的語法,只需將其稱爲

Dictionary[SomeKey] = SomeValue; 
+0

我剛剛發現這個:[不同的方式添加到詞典](http://stackoverflow.com/questions/1838476/different-ways-of-adding-to-dictionary),我認爲是值得的儘管出現錯誤,但作爲一個額外的知識來了解兩者之間的實際區別。再次感謝你 :) –

2

我覺得不同的是:

  • Dictionary[SomeKey] = SomeValue;(不Dictionary.Item[SomeKey] = SomeValue;)將增加新的鍵值對,如果該鍵不存在,如果密鑰存在,它將取代值
  • Dictionary.Add(SomeKey, SomeValue);將增加新的鍵值對,如果鍵已經存在,它會拋出參數異常:具有相同鍵的項已被添加

的例子是:

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); 
}