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 パラメーターの型の既定値。 このパラメーターは初期化せずに渡されます。

返品

指定したキーを持つ要素が に含まれている場合は a0/& 。それ以外の場合は。

実装

例外

keynullです。

この例では、 TryGetValue メソッドを使用して、並べ替えられたリストにないキーを頻繁に試行するプログラムの値を取得するより効率的な方法を示します。 これに対し、この例では、存在しないキーを取得しようとしたときに、 Item[] プロパティ (C# のインデクサー) が例外をスローする方法も示しています。

このコード例は、 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 パラメーターは、整数型の場合はゼロ (0)、ブール型の場合はfalse、参照型の場合はnullなど、値型TValueに適切な既定値を取得します。

このメソッドはバイナリ検索を実行します。したがって、このメソッドは O (ログ n) 操作であり、 nCount

適用対象

こちらもご覧ください