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

定義

判斷 SortedDictionary<TKey,TValue> 是否包含具有指定之索引鍵的項目。

C#
public bool ContainsKey (TKey key);

參數

key
TKey

要在 SortedDictionary<TKey,TValue> 中尋找的索引鍵。

傳回

如果 true 包含具有指定索引鍵的項目,則為 SortedDictionary<TKey,TValue>,否則為 false

實作

例外狀況

keynull

範例

下列程式代碼範例示範如何使用 ContainsKey 方法來測試在呼叫 Add 方法之前是否有索引鍵存在。 它也示範如何使用 TryGetValue 方法來擷取值,這是當程式經常嘗試不在字典中的索引鍵時,擷取值的有效方式。 最後,它會使用 C# ) 中的索引器,以 (屬性來測試索引鍵是否存在 Item[] 最有效率的方式。

此程式代碼範例是針對 類別提供的較大範例的 SortedDictionary<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.");
}

備註

此方法是 O (記錄 n) 作業。

適用於

產品 版本
.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.6, 2.0, 2.1
UWP 10.0

另請參閱