IDictionary<TKey,TValue>.Add(TKey, TValue) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定されたキーと値を持つ要素を IDictionary<TKey,TValue>に追加します。
public:
void Add(TKey key, TValue value);
public void Add(TKey key, TValue value);
abstract member Add : 'Key * 'Value -> unit
Public Sub Add (key As TKey, value As TValue)
パラメーター
- key
- TKey
追加する要素のキーとして使用するオブジェクト。
- value
- TValue
追加する要素の値として使用するオブジェクト。
例外
key は nullです。
同じキーを持つ要素が既に IDictionary<TKey,TValue>に存在します。
例
次のコード例では、整数キーを使用して文字列の空の Dictionary<TKey,TValue> を作成し、 IDictionary<TKey,TValue> インターフェイスを介してアクセスします。 このコード例では、 Add メソッドを使用していくつかの要素を追加します。 この例では、重複するキーを追加しようとしたときに、 Add メソッドが ArgumentException をスローすることを示します。
このコードは、コンパイルして実行できるより大きな例の一部です。 System.Collections.Generic.IDictionary<TKey,TValue>を参照してください。
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<string, string> openWith =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new dictionary of strings, with string keys,
' and access it through the IDictionary generic interface.
Dim openWith As IDictionary(Of String, String) = _
New Dictionary(Of String, String)
' Add some elements to the dictionary. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' The Add method throws an exception if the new key is
' already in the dictionary.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
注釈
Item[] プロパティを使用して、ディクショナリに存在しないキーの値を設定することで、新しい要素を追加することもできます。たとえば、C# の myCollection["myNonexistentKey"] = myValue (Visual Basic では myCollection("myNonexistentKey") = myValue)。 ただし、指定したキーがディクショナリに既に存在する場合は、 Item[] プロパティを設定すると、古い値が上書きされます。 これに対し、 Add メソッドは既存の要素を変更しません。
実装は、オブジェクトの等価性を決定する方法によって異なる場合があります。たとえば、 List<T> クラスは Comparer<T>.Defaultを使用しますが、 Dictionary<TKey,TValue> クラスでは、キーの比較に使用する IComparer<T> 実装をユーザーが指定できます。
実装は、 key を nullできるかどうかによって異なる場合があります。