IDictionary<TKey,TValue>.TryGetValue(TKey, TValue) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定したキーに関連付けられている値を取得します。
public:
bool TryGetValue(TKey key, [Runtime::InteropServices::Out] TValue % value);
public bool TryGetValue(TKey key, out TValue value);
abstract member TryGetValue : 'Key * 'Value -> bool
Public Function TryGetValue (key As TKey, ByRef value As TValue) As Boolean
パラメーター
- key
- TKey
取得する値を持つキー。
- value
- TValue
このメソッドから制御が戻るときに、指定したキーに関連付けられている値 (キーが見つかった場合)。それ以外の場合は、 value パラメーターの型の既定値。 このパラメーターは初期化せずに渡されます。
返品
true
IDictionary<TKey,TValue>を実装するオブジェクトに、指定したキーを持つ要素が含まれている場合は。それ以外の場合はfalse。
例外
key は nullです。
例
この例では、 TryGetValue メソッドを使用して値を取得する方法を示します。 プログラムがディクショナリにないキー値を頻繁に試行する場合、 TryGetValue メソッドは、存在しないキーを取得しようとしたときに例外をスローする Item[] プロパティ (C# のインデクサー) を使用するよりも効率的です。
このコードは、コンパイルして実行できるより大きな例の一部です。 System.Collections.Generic.IDictionary<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
注釈
このメソッドは、 ContainsKey メソッドと Item[] プロパティの機能を組み合わせたものです。
キーが見つからない場合、value パラメーターは、整数型の場合は 0、ブール型の場合は false、参照型の場合はnullなど、TValue型の適切な既定値を取得します。