IDictionary.Add 方法

IDictionary 对象中添加一个带有所提供的键和值的元素。

**命名空间:**System.Collections
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
Sub Add ( _
    key As Object, _
    value As Object _
)
用法
Dim instance As IDictionary
Dim key As Object
Dim value As Object

instance.Add(key, value)
void Add (
    Object key,
    Object value
)
void Add (
    Object^ key, 
    Object^ value
)
void Add (
    Object key, 
    Object value
)
function Add (
    key : Object, 
    value : Object
)

参数

  • key
    用作要添加的元素的键的 Object
  • value
    用作要添加的元素的值的 Object

异常

异常类型 条件

ArgumentNullException

key 为 空引用(在 Visual Basic 中为 Nothing)。

ArgumentException

IDictionary 对象中已存在具有相同键的元素。

NotSupportedException

IDictionary 为只读。

- 或 -

IDictionary 具有固定大小。

备注

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

实现在是否允许键为 空引用(在 Visual Basic 中为 Nothing) 方面有所不同。

示例

下面的代码示例演示如何实现 Add 方法。此代码示例是为 IDictionary 类提供的一个更大示例的一部分。

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
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:
    virtual 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 gcnew InvalidOperationException
                ("The dictionary cannot hold any more items.");
        }
        items[itemsInUse++] = gcnew DictionaryEntry(key, value);
    }

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

IDictionary 接口
IDictionary 成员
System.Collections 命名空间
Item