SortedDictionary<TKey,TValue>.TryGetValue(TKey, TValue) Metodo

Definizione

Ottiene il valore associato alla chiave specificata.

public:
 virtual bool TryGetValue(TKey key, [Runtime::InteropServices::Out] TValue % value);
public bool TryGetValue(TKey key, out TValue value);
abstract member TryGetValue : 'Key * 'Value -> bool
override this.TryGetValue : 'Key * 'Value -> bool
Public Function TryGetValue (key As TKey, ByRef value As TValue) As Boolean

Parametri

key
TKey

Chiave del valore da ottenere.

value
TValue

Quando termina, il valore associato alla chiave specificata, se viene trovata la chiave; in caso contrario, il valore predefinito per il value tipo del parametro.

Valori restituiti

true SortedDictionary<TKey,TValue> se contiene un elemento con la chiave specificata; in caso contrario, false.

Implementazioni

Eccezioni

key è null.

Esempio

Nell'esempio viene illustrato come usare il TryGetValue metodo come modo più efficiente per recuperare i valori in un programma che prova spesso le chiavi che non sono presenti nel dizionario. Al contrario, l'esempio mostra anche come la Item[] proprietà (l'indicizzatore in C#) genera eccezioni quando si tenta di recuperare chiavi inesistente.

Questo esempio di codice fa parte di un esempio più ampio fornito per la SortedDictionary<TKey,TValue> classe .

// 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
// 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

Commenti

Questo metodo combina la funzionalità del ContainsKey metodo e della Item[] proprietà .

Se la chiave non viene trovata, il value parametro ottiene il valore predefinito appropriato per il tipo valore TValue, ad esempio 0 (zero) per i tipi integer, false per i tipi booleani e null per i tipi di riferimento.

Questo metodo è un'operazione O(log n).

Si applica a

Vedi anche