PropertyCollection.IDictionary.Add(Object, Object) Método

Definición

Agrega un elemento con la clave y el valor proporcionados al objeto 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

Parámetros

key
Object

Object que se va a utilizar como clave del elemento que se va a agregar.

value
Object

Object que se va a utilizar como valor del elemento que se va a agregar.

Implementaciones

Excepciones

key es null.

Ya existe un elemento con la misma clave en el objeto IDictionary.

IDictionary es de solo lectura.

o bien

IDictionary tiene un tamaño fijo.

Ejemplos

En el siguiente ejemplo se muestra cómo implementar el método Add. Este ejemplo de código es parte de un ejemplo más grande proporcionado para la clase IDictionary.

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);
    }
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

Comentarios

También puede usar la Item[] propiedad para agregar nuevos elementos estableciendo el valor de una clave que no existe en el diccionario (por ejemplo, myCollection["myNonexistentKey"] = myValue). Sin embargo, si la clave especificada ya existe en el diccionario, al establecer la Item[] propiedad se sobrescribe el valor anterior. En cambio, el Add método no modifica los elementos existentes.

Se aplica a

Consulte también