IDictionary.Add(Object, Object) メソッド

定義

指定されたキーと値を持つ要素を IDictionary オブジェクトに追加します。

public:
 void Add(System::Object ^ key, System::Object ^ value);
public void Add(object key, object value);
abstract member Add : obj * obj -> unit
Public Sub Add (key As Object, value As Object)

パラメーター

key
Object

追加する要素のキーとして使用する Object

value
Object

追加する要素の値として使用する Object

例外

keynullです。

同じキーを持つ要素が、 IDictionary オブジェクトに既に存在します。

IDictionaryは読み取り専用です。

-または-

IDictionaryには固定サイズがあります。

次のコード例は、 Add メソッドを実装する方法を示しています。 このコード例は、 IDictionary クラスに提供されるより大きな例の一部です。

public void Add(object key, object value)
{
    // Add the new key/value pair even if this key already exists in the dictionary.
    if (ItemsInUse == items.Length)
        throw new InvalidOperationException("The dictionary cannot hold any more items.");
    items[ItemsInUse++] = new DictionaryEntry(key, value);
}
Public Sub Add(ByVal key As Object, ByVal value As Object) Implements IDictionary.Add

    ' Add the new key/value pair even if this key already exists in the dictionary.
    If ItemsInUse = items.Length Then
        Throw New InvalidOperationException("The dictionary cannot hold any more items.")
    End If
    items(ItemsInUse) = New DictionaryEntry(key, value)
    ItemsInUse = ItemsInUse + 1
End Sub

注釈

Item[] プロパティを使用して、ディクショナリに存在しないキーの値 (たとえば、myCollection["myNonexistentKey"] = myValue) を設定して、新しい要素を追加することもできます。 ただし、指定したキーがディクショナリに既に存在する場合は、 Item[] プロパティを設定すると、古い値が上書きされます。 これに対し、 Add メソッドは既存の要素を変更しません。

実装は、キーの nullを許可するかどうかによって異なる場合があります。

適用対象

こちらもご覧ください