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

Definición

Determina si IDictionary<TKey,TValue> contiene un elemento con la clave especificada.

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

Devoluciones

Es true si IDictionary<TKey,TValue> contiene un elemento con la clave; en caso contrario, es false.

Excepciones

key es null.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar el ContainsKey método para probar si existe una clave antes de llamar al Add método . También muestra cómo usar el TryGetValue método , que puede ser una manera más eficaz de recuperar valores si un programa prueba con frecuencia los valores de clave que no están en el diccionario. Por último, muestra cómo insertar elementos mediante Item[] la propiedad (el indexador en C#).

Este código forma parte de un ejemplo más grande que se puede compilar y ejecutar. Vea 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 usa Comparer<T>.Default, mientras que la Dictionary<TKey,TValue> clase permite al usuario especificar la IComparer<T> implementación que se va a usar para comparar claves.

Las implementaciones pueden variar en si permiten key ser null.

Se aplica a