SortedDictionary<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 包含具有指定索引鍵的項目,則為 SortedDictionary<TKey,TValue>,否則為 false

實作

例外狀況

keynull

範例

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

此程式碼範例是針對 類別提供的較大範例的 SortedDictionary<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", 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 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 參考型別。

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

適用於

另請參閱