IDictionary.Add(Object, Object) Metodo

Definizione

Aggiunge un elemento con la chiave e il valore specificati all'oggetto IDictionary .

public:
 void Add(System::Object ^ key, System::Object ^ value);
public void Add(object key, object value);
abstract member Add : obj * obj -> unit
Public Sub Add (key As Object, value As Object)

Parametri

key
Object

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

value
Object

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

Eccezioni

key è null.

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

è IDictionary di sola lettura.

oppure

Ha IDictionary una dimensione fissa.

Esempio

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

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, l'impostazione della Item[] proprietà sovrascrive il valore precedente. Al contrario, il Add metodo non modifica gli elementi esistenti.

Le implementazioni possono variare in base al fatto che consentano la chiave come null.

Si applica a

Vedi anche