IDictionary<TKey,TValue>.ContainsKey(TKey) 方法

定义

确定该元素是否 IDictionary<TKey,TValue> 包含具有指定键的元素。

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

参数

key
TKey

要查找到的 IDictionary<TKey,TValue>键。

返回

true 如果包含具有键的元素,则为 IDictionary<TKey,TValue> ;否则为 false

例外

keynull

示例

下面的代码示例演示如何使用 ContainsKey 该方法测试在调用 Add 该方法之前是否存在键。 它还演示如何使用 TryGetValue 该方法,如果程序经常尝试不在字典中的键值,则该方法可以更高效地检索值。 最后,它演示如何使用 Item[] 属性(C# 中的索引器)插入项。

此代码是可以编译和执行的大型示例的一部分。 请参阅 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 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", 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 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

注解

实现在确定对象相等性的方式上可能有所不同;例如,类List<T>使用,而Comparer<T>.Default类允许用户指定用于比较键的Dictionary<TKey,TValue>IComparer<T>实现。

实现因是否允许keynull实现而异。

适用于