Dictionaryへの追加の方法による挙動の違い

C#の、System.Collections.Generic.Dictionary クラスは、重複するキーをAddメソッドで追加しようとすると、例外が飛ぶ。javaのHashMapみたいに上書きしてくれるのを期待してたんですが。。。

System.ArgumentException はハンドルされませんでした。

Message=”同一のキーを含む項目が既に追加されています。”

Item プロパティを使用すると、Dictionary 内に存在しないキーの値を設定することで、新しい要素を追加することもできます (例 : myCollection[myKey] = myValue) (Visual Basic では myCollection(myKey) = myValue)。ただし、指定したキーが Dictionary 内に既に存在する場合、Item プロパティを設定すると既存の値が上書きされます。一方、Add メソッドは、指定したキーを持つ値が既に存在する場合、例外をスローします。

http://msdn2.microsoft.com/ja-jp/library/k7z0zy8k%28VS.80%29.aspx

メソッド経由とインデクサ経由で動作が違うということか。

IDictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "1");
//dict.Add(1, "10"); //-> ArgumentException
dict[1] = "10"; //-> ok

インデクサ経由だと、重複したキーへの追加でも例外が出なくなるようです。

そうゆう仕様にした気持ちはわかるけど、わかりにくい。

3件のコメント

  • Hi there,I check your new stuff named “週記くらい | Dictionaryへの追加の方法による挙動の違い” regularly.Your writing style is awesome, keep it up! And you can look our website about اغانى.

  • I think your page needs some fresh content. Writing manually takes a lot of time, but there is tool for this time consuming task, search for: Boorfe’s tips unlimited content

  • I see you don’t monetize your blog, don’t waste your traffic, you can earn additional bucks every month because you’ve got hi quality content. If you want to know how to make extra bucks, search for: Mertiso’s tips best adsense alternative

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


The reCAPTCHA verification period has expired. Please reload the page.

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください