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

Definizione

Ottiene o imposta l'elemento con la chiave specificata.

public:
 property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); };
public TValue this[TKey key] { get; set; }
member this.Item('Key) : 'Value with get, set
Default Public Property Item(key As TKey) As TValue

Parametri

key
TKey

Chiave dell'elemento da ottenere o impostare.

Valore della proprietà

TValue

Elemento con la chiave specificata.

Eccezioni

key è null.

La proprietà viene recuperata e key non viene trovato.

La proprietà è stata impostata e l'interfaccia IDictionary<TKey,TValue> è in sola lettura.

Esempio

Nell'esempio di codice seguente viene usata la Item[] proprietà (l'indicizzatore in C#) per recuperare i valori, dimostrando che viene generata quando KeyNotFoundException una chiave richiesta non è presente e che è possibile sostituire il valore associato a una chiave.

L'esempio mostra anche come usare il TryGetValue metodo come metodo più efficiente per recuperare i valori se un programma spesso deve provare i valori chiave che non sono nel dizionario.

Questo codice fa parte di un esempio più ampio che può essere compilato ed eseguito. Vedere System.Collections.Generic.IDictionary<TKey,TValue>.

// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console::WriteLine("For key = \"rtf\", value = {0}.",
    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 = {0}.",
    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 Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
    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 = {0}.",
    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 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 indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console::WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException^)
{
    Console::WriteLine("Key = \"tif\" is not found.");
}
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
' The default Item property throws an exception if the requested
' key is not in the dictionary.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
String^ value = "";
if (openWith->TryGetValue("tif", value))
{
    Console::WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console::WriteLine("Key = \"tif\" is not found.");
}
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
' When a program often has to try keys that turn out not to
' be in the dictionary, TryGetValue can be a more efficient 
' way to retrieve values.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
    Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
    Console.WriteLine("Key = ""tif"" is not found.")
End If

Commenti

Questa proprietà consente di accedere a un elemento specifico dell'insieme usando la sintassi seguente: myCollection[key] (myCollection(key) in Visual Basic).

È anche possibile usare la Item[] proprietà per aggiungere nuovi elementi impostando il valore di una chiave che non esiste nel dizionario, myCollection["myNonexistentKey"] = myValue ad esempio in C# (myCollection("myNonexistentKey") = myValue in Visual Basic). 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 modo in cui determinano l'uguaglianza degli oggetti; Ad esempio, la List<T> classe usa Comparer<T>.Default, mentre la Dictionary<TKey,TValue> classe consente all'utente di specificare l'implementazione IComparer<T> da usare per il confronto delle chiavi.

Il linguaggio C# usa la parola chiave per definire gli indicizzatori anziché implementare la Item[] proprietà . In Visual Basic la proprietà Item[] viene implementata come predefinita per fornire la stessa funzionalità di indicizzazione.

Le implementazioni possono variare in base al fatto che consentano key di essere null.

Si applica a

Vedi anche