IDictionary<TKey,TValue>.TryGetValue(TKey, TValue) メソッド

定義

指定したキーに関連付けられている値を取得します。

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

戻り値

指定したキーを持つ要素が IDictionary<TKey,TValue> を実装するオブジェクトに格納されている場合は true、それ以外の場合は false

例外

keynullです。

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

このコードは、コンパイルおよび実行できる大きな例の一部です。 以下を参照してください。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", 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.
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 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 パラメーターは型の適切な既定値 (整数型 TValueの場合は 0、ブール型の場合は 0、 falsenull 参照型の場合は 0) を取得します。

適用対象

こちらもご覧ください