SortedList<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 cujo valor é obter.

value
TValue

Quando este método retorna, o valor associado à chave especificada, se a chave for 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 SortedList<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 na lista ordenada. 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 SortedList<TKey,TValue> classe.

// When a program often has to try keys that turn out not to
// be in the list, 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 list, 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
// When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue("tif") with
| true, value ->
    printfn "For key = \"tif\", value = {value}."
| false, _ ->
    printfn "Key = \"tif\" is not found."
// The indexer throws an exception if the requested key is
// not in the list.
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 list.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// The indexer throws an exception if the requested key is
// not in the list.
try
    printfn $"""For key = "tif", value = {openWith["tif"]}."""
with 
    | :? KeyNotFoundException ->
        printfn "Key = \"tif\" is not found."

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 TValuede valor ; por exemplo, zero (0) para tipos inteiros, false para tipos booleanos e null para tipos de referência.

Este método realiza uma pesquisa binária; portanto, este método é uma operação O(log n), onde n é Count.

Aplica-se a

Ver também