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

Dim instance As IDictionary(Of TKey, TValue) Dim key As TKey Dim returnValue As Boolean returnValue = instance.ContainsKey(key)
戻り値
指定したキーを持つ要素を IDictionary が保持している場合は true。それ以外の場合は false。


オブジェクトが等しいかどうかを判断する方法で実装が異なります。たとえば、List クラスでは Comparer.Default が使用されます。また、Dictionary クラスでは、IComparer 実装をキーの比較に使うかどうかをユーザーが指定できます。
key を null 参照 (Visual Basic では Nothing) にできるかどうかは、実装によって異なります。

Add メソッドを呼び出す前に、ContainsKey メソッドを使用して、キーが存在するかどうかをテストする方法を次のコード例に示します。また、このコード例では、プログラムがディクショナリにないキー値を頻繁に試行する必要がある場合に、最も効率的に値を取得する方法として TryGetValue メソッドを使用する方法も示します。最後に、Item プロパティ (C# の場合はインデクサ) を使用して項目を挿入する方法を示します。
このコードは、コンパイルして実行することのできる例の一部です。詳細については、System.Collections.Generic.IDictionary のトピックを参照してください。
' ContainsKey can be used to test keys before inserting ' them. If Not openWith.ContainsKey("ht") Then openWith.Add("ht", "hypertrm.exe") Console.WriteLine("Value added for key = ""ht"": {0}", _ openWith("ht")) End If <br /><span space="preserve">...</span><br /> ' 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
// ContainsKey can be used to test keys before inserting // them. if (!openWith.ContainsKey("ht")) { openWith.Add("ht", "hypertrm.exe"); Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); } <br /><span space="preserve">...</span><br /> // 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.ContainsKey メソッドのページへのリンク