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

Definição

Obtém o valor associado à chave 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

A chave do valor a obter.

value
TValue

Quando este método retorna, contém o valor associado à chave especificada, caso a chave seja encontrada; caso contrário, o valor padrão para o tipo do value parâmetro. Este parâmetro é passado sem inicializar.

Devoluções

true se o Dictionary<TKey,TValue> contiver um elemento com a chave especificada; caso contrário, false.

Implementações

Exceções

key é null.

Exemplos

O exemplo mostra como usar o TryGetValue método como uma forma mais eficiente de recuperar valores num programa que frequentemente tenta chaves que não estão no dicionário. Para contraste, o exemplo também mostra como a Item[] propriedade (o indexador em C#) lança exceções ao tentar recuperar chaves inexistentes.

Este exemplo de código faz parte de um exemplo maior fornecido para a Dictionary<TKey,TValue> classe (openWith é o nome do Dicionário usado neste exemplo).

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

Observações

Este método combina a funcionalidade do ContainsKey método e a Item[] propriedade.

Se a chave não for encontrada, então o value parâmetro recebe o valor padrão apropriado para o tipo TValue; por exemplo, 0 (zero) para tipos inteiros, false para tipos booleanos e null para tipos de referência.

Use o TryGetValue método se o seu código tentar frequentemente aceder a chaves que não estão no dicionário. Usar este método é mais eficiente do que apanhar o KeyNotFoundException lançado pela Item[] propriedade.

Este método aproxima-se de uma operação O(1).

Aplica-se a

Ver também