Dictionary<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 el método devuelve un valor, contiene el valor asociado a la clave especificada, si se encuentra la clave; en caso contrario, contiene el valor predeterminado para el tipo del parámetro value. Este parámetro se pasa sin inicializar.

Devoluciones

true si la colección Dictionary<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 de un programa que intenta con frecuencia las 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 forma parte de un ejemplo más grande proporcionado para la Dictionary<TKey,TValue> clase (openWith es el nombre del diccionario usado en este ejemplo).

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

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 TValue; por ejemplo, 0 (cero) para los tipos enteros, false para los tipos booleanos y null para los tipos de referencia.

Use el método si el TryGetValue código intenta acceder con frecuencia a las claves que no están en el diccionario. El uso de este método es más eficaz que capturar el KeyNotFoundException producido por la Item[] propiedad .

Este método se aproxima a una operación de O(1).

Se aplica a

Consulte también