IDictionary<TKey,TValue>.ContainsKey(TKey) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定したキーを持つ要素が IDictionary<TKey,TValue> に含まれているかどうかを判断します。
public:
bool ContainsKey(TKey key);
public bool ContainsKey(TKey key);
abstract member ContainsKey : 'Key -> bool
Public Function ContainsKey (key As TKey) As Boolean
パラメーター
- key
- TKey
IDictionary<TKey,TValue>内で検索するキー。
返品
true キーを持つ要素が IDictionary<TKey,TValue> に含まれている場合は。それ以外の場合は false。
例外
key は nullです。
例
次のコード例は、 ContainsKey メソッドを使用して、 Add メソッドを呼び出す前にキーが存在するかどうかをテストする方法を示しています。 また、 TryGetValue メソッドの使用方法についても説明します。これは、プログラムがディクショナリにないキー値を頻繁に試行する場合に、より効率的に値を取得する方法です。 最後に、 Item[] プロパティ (C# のインデクサー) を使用して項目を挿入する方法を示します。
このコードは、コンパイルして実行できるより大きな例の一部です。 System.Collections.Generic.IDictionary<TKey,TValue>を参照してください。
// 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"]);
}
' 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
// 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
注釈
実装は、オブジェクトの等価性を決定する方法によって異なる場合があります。たとえば、 List<T> クラスは Comparer<T>.Defaultを使用しますが、 Dictionary<TKey,TValue> クラスでは、キーの比較に使用する IComparer<T> 実装をユーザーが指定できます。
実装は、 key を nullできるかどうかによって異なる場合があります。