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

Definición

Determina si IDictionary<TKey,TValue> contiene un elemento con la clave 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

Clave que se buscará en IDictionary<TKey,TValue>.The key to locate in the IDictionary<TKey,TValue>.

Devoluciones

Boolean

Es true si IDictionary<TKey,TValue> contiene un elemento con la clave; en caso contrario, es false.true if the IDictionary<TKey,TValue> contains an element with the key; otherwise, false.

Excepciones

key es null.key is null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar el ContainsKey método para comprobar si existe una clave antes de llamar al Add 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. También se muestra cómo usar el TryGetValue método, que puede ser una forma más eficaz de recuperar valores si un programa intenta con frecuencia valores de clave que no están en el diccionario.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 último, se muestra cómo insertar elementos con Item[] la propiedad (el indizador en C#).Finally, it shows how to insert items using Item[] property (the indexer in C#).

Este código forma parte de un ejemplo más grande que se puede compilar y ejecutar.This code is part of a larger example that can be compiled and executed. Vea 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

Comentarios

Las implementaciones pueden variar en la forma en que determinan la igualdad de objetos; por ejemplo, la List<T> clase utiliza Comparer<T>.Default , mientras que la Dictionary<TKey,TValue> clase permite al usuario especificar la IComparer<T> implementación que se va a utilizar para comparar las claves.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.

Las implementaciones pueden variar en lo que se key requieran null .Implementations can vary in whether they allow key to be null.

Se aplica a