PropertyCollection.IDictionary.Add(Object, Object) 方法

定义

将具有提供的键和值的元素添加到 IDictionary 对象。

 virtual void System.Collections.IDictionary.Add(System::Object ^ key, System::Object ^ value) = System::Collections::IDictionary::Add;
void IDictionary.Add(object key, object value);
abstract member System.Collections.IDictionary.Add : obj * obj -> unit
override this.System.Collections.IDictionary.Add : obj * obj -> unit
Sub Add (key As Object, value As Object) Implements IDictionary.Add

参数

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

注解

还可以通过设置字典中不存在的键的值(例如,myCollection["myNonexistentKey"] = myValue)来使用该Item[]属性来添加新元素。 但是,如果指定的键已存在于字典中,则设置该 Item[] 属性将覆盖旧值。 相反,该方法 Add 不会修改现有元素。

适用于

另请参阅