PropertyCollection.IDictionary.Add(Object, Object) Metodo

Definizione

Aggiunge un elemento con la chiave e il valore forniti all'oggetto 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

Parametri

key
Object

Oggetto Object da usare come chiave dell'elemento da aggiungere.

value
Object

Oggetto Object da usare come valore dell'elemento da aggiungere.

Implementazioni

Eccezioni

key è null.

Un elemento con la stessa chiave esiste già nell'oggetto IDictionary.

La classe IDictionary è di sola lettura.

-oppure-

Le dimensioni dell'oggetto IDictionary sono fisse.

Esempio

Nell'esempio seguente viene illustrato come implementare il metodo Add. Questo esempio di codice fa parte di un esempio più grande fornito per la IDictionary classe.

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

Commenti

È anche possibile usare la Item[] proprietà per aggiungere nuovi elementi impostando il valore di una chiave che non esiste nel dizionario , ad esempio myCollection["myNonexistentKey"] = myValue. Tuttavia, se la chiave specificata esiste già nel dizionario, impostando la proprietà sovrascrive il Item[] valore precedente. Al contrario, il Add metodo non modifica gli elementi esistenti.

Si applica a

Vedi anche