SortedDictionary<TKey,TValue>.TryGetValue(TKey, TValue) Método

Definición

Obtiene el valor asociado a la clave especificada.

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

Parámetros

key
TKey

Clave del valor que se va a obtener.

value
TValue

Cuando este método devuelve el resultado, el valor asociado a la clave especificada, si se encuentra la clave; en caso contrario, el valor predeterminado para el tipo del parámetro value.

Devoluciones

true si la colección SortedDictionary<TKey,TValue> contiene un elemento con la clave especificada; en caso contrario, false.

Implementaciones

Excepciones

key es null.

Ejemplos

En el ejemplo se muestra cómo usar el TryGetValue método como una manera más eficaz de recuperar valores en un programa que con frecuencia intenta claves que no están en el diccionario. Por el contrario, en el ejemplo también se muestra cómo la Item[] propiedad (el indexador en C#) produce excepciones al intentar recuperar claves inexistentes.

Este ejemplo de código es parte de un ejemplo más grande proporcionado para la clase SortedDictionary<TKey,TValue>.

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

Comentarios

Este método combina la funcionalidad del ContainsKey método y la Item[] propiedad .

Si no se encuentra la clave, el value parámetro obtiene el valor predeterminado adecuado para el tipo TValuede valor ; por ejemplo, 0 (cero) para los tipos enteros, false para los tipos booleanos y null para los tipos de referencia.

Este método es una operación de O(log n).

Se aplica a

Consulte también