IDictionary.Add(Object, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將所提供的鍵值與值加入一個元素到物件上 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 是 null。
物件中已經 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。