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

Definição

Obtém o valor associado à chave especificada.

public:
 bool TryGetValue(TKey key, [Runtime::InteropServices::Out] TValue % value);
public bool TryGetValue (TKey key, out TValue value);
abstract member TryGetValue : 'Key * 'Value -> bool
Public Function TryGetValue (key As TKey, ByRef value As TValue) As Boolean

Parâmetros

key
TKey

A chave cujo valor será obtido.

value
TValue

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

Retornos

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

Exceções

key é null.

Exemplos

O exemplo mostra como usar o TryGetValue método para recuperar valores. Se um programa frequentemente tenta valores de chave que não estão em um dicionário, o TryGetValue método pode ser mais eficiente do que usar a Item[] propriedade (o indexador em C#), que gera exceções ao tentar recuperar chaves inexistentes.

Esse código faz parte de um exemplo maior que pode ser compilado e executado. Consulte System.Collections.Generic.IDictionary<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", 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, zero (0) para tipos inteiros, false para tipos boolianos e null para tipos de referência.

Aplica-se a

Confira também