Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) 方法

定義

取得與指定索引鍵關聯的值。

C#
public bool TryGetValue (TKey key, out TValue value);

參數

key
TKey

要取得之值的索引鍵。

value
TValue

這個方法傳回時,如果找到索引鍵,則包含與指定索引鍵相關聯的值,否則為 value 參數類型的預設值。 這個參數會以未初始化的狀態傳遞。

傳回

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

實作

例外狀況

keynull

範例

此範例示範如何使用 TryGetValue 方法作為更有效率的方式,以擷取經常嘗試字典中索引鍵的程式值。 相反地,此範例也會示範屬性如何 Item[] (C# ) 嘗試擷取不存在的索引鍵時擲回例外狀況。

此程式代碼範例是針對 Dictionary<TKey,TValue> 類別提供的較大範例的一部分, openWith (是本範例中使用的 Dictionary 名稱) 。

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.");
}

備註

這個方法結合了 方法和 Item[] 屬性的功能ContainsKey

如果找不到索引鍵,則 value 參數會取得類型 TValue的適當預設值;例如,0 (整數類型的零) 、 false 布爾類型,以及 null 參考型別。

TryGetValue如果您的程式代碼經常嘗試存取不在字典中的索引鍵,請使用 方法。 使用此方法比擷 KeyNotFoundException 取 屬性擲 Item[] 回的 更有效率。

此方法會接近 O (1) 作業。

適用於

產品 版本
.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

另請參閱