Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
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, contiene el valor asociado a la clave especificada, si se encuentra la clave; de lo contrario, el valor predeterminado para el tipo del value parámetro . Este parámetro se pasa sin inicializar.
Devoluciones
true
Dictionary<TKey,TValue> si contiene un elemento con la clave especificada; de lo 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 intenta con frecuencia claves que no están en el diccionario. Por el contrario, en el ejemplo también se muestra cómo la Item[] propiedad (el indizador 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", 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.
match openWith.TryGetValue "tif" with
| true, value -> printfn $"For key = \"tif\", value = {value}."
| _ -> printfn "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
printfn $"""For key = "tif", value = {openWith["tif"]}"""
with :? KeyNotFoundException ->
printfn "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 TryGetValue método si el 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).