IDictionary<TKey,TValue>.ContainsKey(TKey) IDictionary<TKey,TValue>.ContainsKey(TKey) IDictionary<TKey,TValue>.ContainsKey(TKey) IDictionary<TKey,TValue>.ContainsKey(TKey) Method

Definição

Determina se o IDictionary<TKey,TValue> contém um elemento com a chave especificada.Determines whether the IDictionary<TKey,TValue> contains an element with the specified key.

public:
 bool ContainsKey(TKey key);
public bool ContainsKey (TKey key);
abstract member ContainsKey : 'Key -> bool
Public Function ContainsKey (key As TKey) As Boolean

Parâmetros

key
TKey TKey TKey TKey

A chave a ser localizada no IDictionary<TKey,TValue>.The key to locate in the IDictionary<TKey,TValue>.

Retornos

true se o IDictionary<TKey,TValue> contiver um elemento com a chave; caso contrário, false.true if the IDictionary<TKey,TValue> contains an element with the key; otherwise, false.

Exceções

Exemplos

O exemplo de código a seguir mostra como usar ContainsKey o método para testar se uma chave existe antes de chamar Add o método.The following code example shows how to use the ContainsKey method to test whether a key exists prior to calling the Add method. Ele também mostra como usar o TryGetValue método, que pode ser uma maneira mais eficiente de recuperar valores se um programa tentar com frequência valores de chave que não estão no dicionário.It also shows how to use the TryGetValue method, which can be a more efficient way to retrieve values if a program frequently tries key values that are not in the dictionary. Por fim, ele mostra como inserir itens usando Item[TKey] a propriedade (o indexador C#em).Finally, it shows how to insert items using Item[TKey] property (the indexer in C#).

Esse código é parte de um exemplo maior que pode ser compilado e executado.This code is part of a larger example that can be compiled and executed. Consulte System.Collections.Generic.IDictionary<TKey,TValue>.See System.Collections.Generic.IDictionary<TKey,TValue>.

// ContainsKey can be used to test keys before inserting
// them.
if (!openWith->ContainsKey("ht"))
{
    openWith->Add("ht", "hypertrm.exe");
    Console::WriteLine("Value added for key = \"ht\": {0}",
        openWith["ht"]);
}
// ContainsKey can be used to test keys before inserting 
// them.
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("Value added for key = \"ht\": {0}", 
        openWith["ht"]);
}
' ContainsKey can be used to test keys before inserting 
' them.
If Not openWith.ContainsKey("ht") Then
    openWith.Add("ht", "hypertrm.exe")
    Console.WriteLine("Value added for key = ""ht"": {0}", _
        openWith("ht"))
End If
// 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

As implementações podem variar na forma como determinam a igualdade dos objetos; por exemplo, a List<T> classe usa Comparer<T>.Default, enquanto a Dictionary<TKey,TValue> classe permite que o usuário especifique a IComparer<T> implementação a ser usada para comparar as chaves.Implementations can vary in how they determine equality of objects; for example, the List<T> class uses Comparer<T>.Default, whereas the Dictionary<TKey,TValue> class allows the user to specify the IComparer<T> implementation to use for comparing keys.

As implementações podem variar se permitirem key. nullImplementations can vary in whether they allow key to be null.

Aplica-se a