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 パラメーターの型の既定値。 このパラメーターは初期化せずに渡されます。
返品
実装
例外
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", 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.
match openWith.TryGetValue "tif" with
| true, value -> printfn $"For key = \"tif\", value = {value}."
| _ -> printfn "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
printfn $"""For key = "tif", value = {openWith["tif"]}"""
with :? KeyNotFoundException ->
printfn "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
注釈
このメソッドは、 ContainsKey メソッドと Item[] プロパティの機能を組み合わせたものです。
キーが見つからない場合、value パラメーターは、整数型の場合は 0 (ゼロ)、ブール型の場合はfalse、参照型の場合はnullなど、TValue型に適した既定値を取得します。
コードがディクショナリにないキーへのアクセスを頻繁に試みる場合は、 TryGetValue メソッドを使用します。 このメソッドを使用すると、Item[] プロパティによってスローされたKeyNotFoundExceptionをキャッチするよりも効率的です。
このメソッドは O(1) 操作に近づく。