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

Dim instance As Dictionary(Of TKey, TValue) Dim key As TKey Dim value As TValue Dim returnValue As Boolean returnValue = instance.TryGetValue(key, value)
public final boolean TryGetValue ( TKey key, /** @attribute OutAttribute() */ /** @ref */ TValue value )
- value
このメソッドから制御が戻るときに、キーが見つかった場合は、指定したキーに関連付けられている値が格納されます。それ以外の場合は value パラメータの型に対する既定の値。このパラメータは初期化せずに渡されます。
指定したキーを持つ要素が Dictionary に格納されている場合は true。それ以外の場合は false。


このメソッドは、ContainsKey メソッドの機能と Item プロパティを組み合わせます。
キーが見つからない場合、value パラメータは、値型 TValue に対する適切な既定値 (整数型には 0 (ゼロ)、ブール型には false、参照型には null 参照 (Visual Basic では Nothing) など) を取得します。
コードがディクショナリにないキーへのアクセスを頻繁に試行する場合は、TryGetValue メソッドを使用します。このメソッドを使用した方が、Item プロパティによってスローされた KeyNotFoundException をキャッチするよりも効率的です。

この例では、プログラムがディクショナリにないキーを頻繁に試行する場合に、より効率的に値を取得する方法として TryGetValue メソッドを使用する方法を示します。これに対して、この例では、存在しないキーの取得を試みた場合に、Item プロパティ (C# ではインデクサ) がどのように例外をスローするかも示します。
このコード例は、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. 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 によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Dictionary ジェネリック クラス
Dictionary メンバ
System.Collections.Generic 名前空間
Dictionary.ContainsKey メソッド
Item
Weblioに収録されているすべての辞書からDictionary.TryGetValue メソッドを検索する場合は、下記のリンクをクリックしてください。

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