SortedList<TKey,TValue>.Item[TKey] Proprietà
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Ottiene o imposta il valore associato alla 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 di cui ottenere o impostare il valore.
Valore della proprietà
Valore associato alla chiave specificata. Se la chiave specificata non viene trovata, un'operazione get genera un'eccezione KeyNotFoundException e un'operazione set crea un nuovo elemento usando la chiave specificata.
Implementazioni
Eccezioni
key è null.
La proprietà viene recuperata e key non esiste nell'insieme.
Esempio
Nell'esempio di codice seguente viene usata la Item[] proprietà (l'indicizzatore in C#) per recuperare i valori, dimostrando che viene generata un'eccezione KeyNotFoundException quando una chiave richiesta non è presente e che il valore associato a una chiave può essere sostituito.
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 si trovano nell'elenco ordinato.
Questo esempio di codice fa parte di un esempio più ampio fornito per la SortedList<TKey,TValue> classe .
// 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 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 throws an exception if the requested key is
// not in the list.
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 list.
Try
Console.WriteLine("For key = ""tif"", value = {0}.", _
openWith("tif"))
Catch
Console.WriteLine("Key = ""tif"" is not found.")
End Try
// The indexer throws an exception if the requested key is
// not in the list.
try
printfn $"""For key = "tif", value = {openWith["tif"]}."""
with
| :? KeyNotFoundException ->
printfn "Key = \"tif\" is not found."
// When a program often has to try keys that turn out not to
// be in the list, 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 list, 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
// When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue("tif") with
| true, value ->
printfn "For key = \"tif\", value = {value}."
| false, _ ->
printfn "Key = \"tif\" is not found."
Commenti
Questa proprietà consente di accedere a un elemento specifico dell'insieme usando la sintassi seguente: myCollection[key].
Una chiave non può essere , ma un valore può essere null, se il tipo di valori nell'elenco, TValue, è un tipo riferimento.
Se la chiave non viene trovata quando viene recuperato un valore, KeyNotFoundException viene generata. Se la chiave non viene trovata quando viene impostato un valore, la chiave e il valore vengono aggiunti.
È anche possibile utilizzare la Item[] proprietà per aggiungere nuovi elementi impostando il valore di una chiave che non esiste in SortedList<TKey,TValue>, ad esempio myCollection["myNonexistentKey"] = myValue. Tuttavia, se la chiave specificata esiste già in , l'impostazione SortedList<TKey,TValue>della Item[] proprietà sovrascrive il valore precedente. Al contrario, il Add metodo non modifica gli elementi esistenti.
Il linguaggio C# usa la this parola chiave per definire gli indicizzatori anziché implementare la Item[] proprietà . Visual Basic implementa Item[] come proprietà predefinita, che fornisce la stessa funzionalità di indicizzazione.
Il recupero del valore di questa proprietà è un'operazione O(log n), dove n è Count. L'impostazione della proprietà è un'operazione O(log n) se la chiave è già presente in SortedList<TKey,TValue>. Se la chiave non è presente nell'elenco, l'impostazione della proprietà è un'operazione O(n) per i dati non ordinato o O(log n) se il nuovo elemento viene aggiunto alla fine dell'elenco. Se l'inserimento causa un ridimensionamento, l'operazione è O(n).