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

定義

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

public:
 virtual bool TryGetValue(TKey key, [Runtime::InteropServices::Out] TValue % value);
public bool TryGetValue (TKey key, out TValue value);
abstract member TryGetValue : 'Key * 'Value -> bool
override this.TryGetValue : 'Key * 'Value -> bool
Public Function TryGetValue (key As TKey, ByRef value As TValue) As Boolean

參數

key
TKey

要取得之值的索引鍵。

value
TValue

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

傳回

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

實作

例外狀況

keynull

範例

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

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

// 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", 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.
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 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

備註

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

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

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

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

適用於

另請參閱