IDictionary.TryGetValue メソッド
アセンブリ: mscorlib (mscorlib.dll 内)

Dim instance As IDictionary(Of TKey, TValue) Dim key As TKey Dim value As TValue Dim returnValue As Boolean returnValue = instance.TryGetValue(key, value)
- value
このメソッドが返されるときに、キーが見つかった場合は、指定したキーに関連付けられている値。それ以外の場合は value パラメータの型に対する既定の値。このパラメータは初期化せずに渡されます。
指定したキーを持つ要素が IDictionary を実装するオブジェクトに格納されている場合は true。それ以外の場合は false。


このメソッドは、ContainsKey メソッドの機能と Item プロパティを組み合わせます。
キーが見つからない場合、value パラメータは、値型 V に対する適切な既定値 (整数型にはゼロ (0)、ブール型には false、参照型には null 参照 (Visual Basic では Nothing) など) を取得します。

この例では、TryGetValue メソッドを使用して値を取得する方法を示します。プログラムがディクショナリにないキー値を頻繁に試行する場合は、存在しないキーを取得しようとすると例外がスローされる Item プロパティ (C# の場合はインデクサ) よりも、TryGetValue メソッドを使用するほうが効率的です。
このコードは、コンパイルして実行することのできる例の一部です。詳細については、System.Collections.Generic.IDictionary のトピックを参照してください。
' 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 <br /><span space="preserve">...</span><br /> ' 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
// 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."); } <br /><span space="preserve">...</span><br /> // 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."); }

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


- IDictionary.TryGetValue メソッドのページへのリンク