語言

SortedList<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 若 包含 SortedList<TKey,TValue> 具有指定鍵的元素;否則, false。

實作

例外狀況

key 是 null。

範例

範例展示了如何將此 TryGetValue 方法作為更有效率的方式,在經常嘗試不在排序列表中的鍵的程式中取得值。 相對地,範例也顯示了該屬性(C# 中的索引器)在 Item[] 嘗試檢索不存在的鍵時拋出異常。

此程式碼範例是本類別更大範例 SortedList<TKey,TValue> 的一部分。

// When a program often has to try keys that turn out not to
// be in the list, 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 list, 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
// When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue("tif") with
| true, value ->
    printfn "For key = \"tif\", value = {value}."
| false, _ ->
    printfn "Key = \"tif\" is not found."
// The indexer throws an exception if the requested key is
// not in the list.
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 list.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// The indexer throws an exception if the requested key is
// not in the list.
try
    printfn $"""For key = "tif", value = {openWith["tif"]}."""
with 
    | :? KeyNotFoundException ->
        printfn "Key = \"tif\" is not found."

備註

此方法結合 ContainsKey 了方法的功能與屬性 Item[] 。

若找不到該鍵,則 value 該參數將獲得該值類型的 TValue適當預設值;例如,整數類型 false 為零(0),布林類型 null 為零,參考型別為零。

此方法執行二分搜尋;因此,此方法是一個 O(log n) 運算,其中 n 為 Count。

適用於

另請參閱