語言

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。

例外狀況

key 是 null。

範例

以下程式碼範例說明如何在呼叫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> 用於比較鍵的實作。

實作方式可能有所不同,是否允許 key 。null

適用於