PropertyCollection.IDictionary.Add(Object, Object) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将具有提供的键和值的元素添加到 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 是 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
注解
还可以通过设置字典中不存在的键的值(例如,myCollection["myNonexistentKey"] = myValue)来使用该Item[]属性来添加新元素。 但是,如果指定的键已存在于字典中,则设置该 Item[] 属性将覆盖旧值。 相反,该方法 Add 不会修改现有元素。