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 ser obtido.

value
TValue

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

Retornos

Boolean

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 maneira mais eficiente de recuperar valores em um programa que frequentemente tenta chaves que não estão no dicionário. Por outro lado, o exemplo também mostra como a Item[] propriedade (o indexador em C#) gera 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", 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

Comentários

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

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

Use o método se o TryGetValue código frequentemente tentar acessar chaves que não estão no dicionário. Usar esse método é mais eficiente do que capturar o KeyNotFoundException gerado pela Item[] propriedade.

Este método abrange uma operação O(1).

Aplica-se a

Confira também