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

定义

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

C#
public bool ContainsKey (TKey key);

参数

key
TKey

要在 IDictionary<TKey,TValue> 中定位的键。

返回

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

例外

keynull

示例

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

此代码是可以编译和执行的更大示例的一部分。 请参阅 System.Collections.Generic.IDictionary<TKey,TValue>

C#
// 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"]);
}
C#
// 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.");
}
C#
// 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.");
}

注解

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

实现在是否允许 keynull方面可能会有所不同。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0