Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得與指定索引鍵關聯的值。
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
。
實作
例外狀況
key
為 null
。
範例
此範例示範如何使用 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) 作業。