語言

IDictionary.Add(Object, Object) 方法

定義

將所提供的鍵值與值加入一個元素到物件上 IDictionary 。

public:
 void Add(System::Object ^ key, System::Object ^ value);
public void Add(object key, 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用 來作為要加的元素值。

例外狀況

key 是 null。

物件中已經 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 方法不會修改現有元素。

實作中是否允許 key 為 null。

適用於

另請參閱