讀的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 answer和MSDN - Dictionary來解決錯誤。
代碼是好的,但出於好奇我是否做錯了什麼?除了一個沒有編制,是什麼
Dictionary.Item[SomeKey] = SomeValue;
和
Dictionary.Add(SomeKey, SomeValue);
之間的區別編輯:
我編輯接受的答案在C# Java HashMap equivalent。查看版本歷史知道原因。
如果字典中已經包含SomeKey,而前者不會,則後者將拋出DuplicateKeyException。把它看作AddOrUpdate。 –
This first:Dictionary.Item [SomeKey] = SomeValue;是要更改字典中已有的值。另一種是將新項目添加到字典中。 – jdweng
至於你的錯誤,只是省略Item,像這樣:myDictionary [SomeKey] = SomeValue; – Evk