共用方式為


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

定義

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

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

參數

key
TKey

要取得其值的索引鍵。

value
TValue

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

傳回

如果實作 IDictionary<TKey,TValue> 之物件包含具有指定索引鍵的元素,則為 true,否則為 false

例外狀況

keynull

範例

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

此程式代碼是可編譯和執行之較大範例的一部分。 請參閱 System.Collections.Generic.IDictionary<TKey,TValue>

// 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 參考型別。

適用於

另請參閱