Dictionary<TKey,TValue>.IDictionary.Item[Object] Proprietà

Definizione

Ottiene o imposta il valore con la chiave specificata.

property System::Object ^ System::Collections::IDictionary::Item[System::Object ^] { System::Object ^ get(System::Object ^ key); void set(System::Object ^ key, System::Object ^ value); };
object System.Collections.IDictionary.Item[object key] { get; set; }
member this.System.Collections.IDictionary.Item(obj) : obj with get, set
 Property Item(key As Object) As Object Implements IDictionary.Item

Parametri

key
Object

Chiave del valore da ottenere.

Valore della proprietà

Valore associato alla chiave specificata oppure null se key non è presente nel dizionario o key è di un tipo che non è assegnabile al tipo TKey di chiave dell'oggetto Dictionary<TKey,TValue>.

Implementazioni

Eccezioni

key è null.

Viene assegnato un valore e key è di un tipo che non è assegnabile al tipo TKey di chiave dell'oggetto Dictionary<TKey,TValue>.

oppure

Viene assegnato un valore e è di un tipo che non è assegnabile al tipo TValue di valore di Dictionary<TKey,TValue>.

Esempio

Nell'esempio di codice seguente viene illustrato come usare la IDictionary.Item[] proprietà (l'indicizzatore in C#) dell'interfaccia System.Collections.IDictionary con un Dictionary<TKey,TValue>oggetto e i modi in cui la proprietà differisce dalla Dictionary<TKey,TValue>.Item[] proprietà .

L'esempio mostra che, come la Dictionary<TKey,TValue>.Item[] proprietà , la Dictionary<TKey,TValue>.IDictionary.Item[] proprietà può modificare il valore associato a una chiave esistente e può essere usato per aggiungere una nuova coppia chiave/valore se la chiave specificata non è presente nel dizionario. L'esempio mostra anche che, a differenza della Dictionary<TKey,TValue>.Item[] proprietà , la Dictionary<TKey,TValue>.IDictionary.Item[] proprietà non genera un'eccezione se key non è presente nel dizionario, restituendo invece un riferimento Null. Infine, l'esempio dimostra che il recupero della Dictionary<TKey,TValue>.IDictionary.Item[] proprietà restituisce un riferimento Null se key non è il tipo di dati corretto e che l'impostazione della proprietà genera un'eccezione se key non è il tipo di dati corretto.

using System;
using System.Collections;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys,
        // and access it using the IDictionary interface.
        //
        IDictionary openWith = new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        // IDictionary.Add throws an exception if incorrect types
        // are supplied for key or value.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Item property is another name for the indexer, so you
        // can omit its name when accessing elements.
        Console.WriteLine($"""For key = "rtf", value = {openWith["rtf"]}.""");

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine($"""For key = "rtf", value = {openWith["rtf"]}.""");

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer returns null if the key is of the wrong data
        // type.
        Console.WriteLine("The indexer returns null"
            + " if the key is of the wrong type:");
        Console.WriteLine($"For key = 2, value = {openWith[2]}.");

        // The indexer throws an exception when setting a value
        // if the key is of the wrong data type.
        try
        {
            openWith[2] = "This does not get added.";
        }
        catch (ArgumentException)
        {
            Console.WriteLine("A key of the wrong type was specified"
                + " when assigning to the indexer.");
        }

        // Unlike the default Item property on the Dictionary class
        // itself, IDictionary.Item does not throw an exception
        // if the requested key is not in the dictionary.
        Console.WriteLine($"""For key = "tif", value = {openWith["tif"]}.""");
    }
}
open System
open System.Collections
open System.Collections.Generic

// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
let openWith: IDictionary = Dictionary<string, string>()

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
// IDictionary.Add throws an exception if incorrect types
// are supplied for key or value.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
printfn $"""For key = "rtf", value = {openWith.["rtf"]}."""

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] <- "winword.exe"
printfn $"""For key = "rtf", value = {openWith.["rtf"]}."""

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] <- "winword.exe"

// The indexer returns null if the key is of the wrong data
// type.
printfn "The indexer returns null if the key is of the wrong type:"
printfn $"""For key = 2, value = {openWith.[2]}."""

// The indexer throws an exception when setting a value
// if the key is of the wrong data type.
try
    openWith[2] <- "This does not get added."
with :? ArgumentException ->
    printfn "A key of the wrong type was specified when assigning to the indexer."

// Unlike the default Item property on the Dictionary class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the dictionary.
printfn $"""For key = "tif", value = {openWith.["tif"]}."""
Imports System.Collections
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new dictionary of strings, with string keys,
        ' and access it using the IDictionary interface.
        '
        Dim openWith As IDictionary = _
            New Dictionary(Of String, String)
        
        ' Add some elements to the dictionary. There are no 
        ' duplicate keys, but some of the values are duplicates.
        ' IDictionary.Add throws an exception if incorrect types
        ' are supplied for key or value.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' The default Item property returns Nothing if the key
        ' is of the wrong data type.
        Console.WriteLine("The default Item property returns Nothing" _
            & " if the key is of the wrong type:")
        Console.WriteLine("For key = 2, value = {0}.", _
            openWith(2))

        ' The default Item property throws an exception when setting
        ' a value if the key is of the wrong data type.
        Try
            openWith(2) = "This does not get added."
        Catch 
            Console.WriteLine("A key of the wrong type was specified" _
                & " when setting the default Item property.")
        End Try

        ' Unlike the default Item property on the Dictionary class
        ' itself, IDictionary.Item does not throw an exception
        ' if the requested key is not in the dictionary.
        Console.WriteLine("For key = ""tif"", value = {0}.", _
            openWith("tif"))

    End Sub

End Class

Commenti

Questa proprietà consente di accedere a un valore specifico nella raccolta usando la sintassi C# seguente: myCollection[key] (myCollection(key) in Visual Basic).

È anche possibile utilizzare la Item[] proprietà per aggiungere nuovi elementi impostando il valore di una chiave che non esiste nel dizionario, myCollection["myNonexistentKey"] = myValuead esempio . 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.

Il linguaggio C# usa la parola chiave per definire gli indicizzatori anziché implementare la IDictionary.Item[] proprietà . Visual Basic implementa IDictionary.Item[] come proprietà predefinita, che fornisce la stessa funzionalità di indicizzazione.

Ottenere o impostare il valore di questa proprietà si avvicina a un'operazione O(1).

Si applica a

Vedi anche