語言

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

定義

判斷是否 SortedDictionary<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

鑰匙要在 SortedDictionary<TKey,TValue>.

傳回

true 若 包含 SortedDictionary<TKey,TValue> 具有指定鍵的元素;否則, false。

實作

例外狀況

key 是 null。

範例

以下程式碼範例說明如何在呼叫ContainsKey方法前,使用Add該方法測試是否存在金鑰。 它也展示了如何使用此 TryGetValue 方法來檢索值,這是程式經常嘗試字典中不在金鑰時,取得值的有效方法。 最後,它展示了測試鍵值是否存在的最低效率方法,方法是使用 Item[] 屬性(C# 中的索引器)。

此程式碼範例是本類別更大範例 SortedDictionary<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

備註

此方法為 O(log n) 操作。

適用於

另請參閱