Dictionary<TKey,TValue>.ContainsKey(TKey) Метод

Определение

Определяет, содержится ли указанный ключ в словаре Dictionary<TKey,TValue>.

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

Параметры

key
TKey

Ключ, который требуется найти в Dictionary<TKey,TValue>.

Возвращаемое значение

true, если Dictionary<TKey,TValue> содержит элемент с указанным ключом, в противном случае — false.

Реализации

Исключения

key имеет значение null.

Примеры

В следующем примере кода показано, как использовать ContainsKey метод для проверки наличия ключа перед вызовом Add метода . Здесь также показано, как использовать TryGetValue метод для получения значений, что является эффективным способом получения значений, когда программа часто пытается использовать ключи, которых нет в словаре. Наконец, он показывает наименее эффективный способ проверки наличия ключей с помощью Item[] свойства (индексатор в C#).

Этот пример кода является частью более крупного примера, предоставленного Dictionary<TKey,TValue> для класса (openWith — это имя словаря, используемого в этом примере).

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

Комментарии

Этот метод подходит к операции O(1).

Применяется к

См. также раздел