Dictionary<TKey,TValue>.Item[TKey] プロパティ

定義

指定されたキーに関連付けられている値を取得または設定します。Gets or sets the value associated with the specified key.

public:
 property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); };
public TValue this[TKey key] { get; set; }
member this.Item('Key) : 'Value with get, set
Default Public Property Item(key As TKey) As TValue

パラメーター

key
TKey

取得または設定する値のキー。The key of the value to get or set.

プロパティ値

TValue

指定されたキーに関連付けられている値。The value associated with the specified key. 指定したキーが見つからなかった場合、get 操作は KeyNotFoundException をスローし、set 操作は指定したキーを持つ新しい要素を作成します。If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

実装

例外

keynull です。key is null.

プロパティが取得され、key がコレクションに存在しません。The property is retrieved and key does not exist in the collection.

注意

この記事の C# 例の一部は、Try.NET インライン コード ランナーとプレイグラウンドで実行されます。Some of the C# examples in this article run in the Try.NET inline code runner and playground. [実行] ボタンがある場合は、これを選択して対話型ウィンドウで例を実行します。When present, select the Run button to run an example in an interactive window. コードを実行したら、コードを変更し、 [実行] をもう一度選択して変更後のコードを実行できます。Once you execute the code, you can modify it and run the modified code by selecting Run again. 変更後のコードが対話型ウィンドウで実行されるか、コンパイルできなかった場合、対話型ウィンドウにすべての C# コンパイラ エラー メッセージが表示されます。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

次のコード例では、Item[TKey] プロパティ (のC#インデクサー) を使用して値を取得し、要求されたキーが存在しない場合に KeyNotFoundException がスローされ、キーに関連付けられている値を置き換えることができることを示しています。The following code example uses the Item[TKey] property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

また、この例では、プログラムがディクショナリに含まれていないキー値を試す必要がある場合に、値を取得するより効率的な方法として TryGetValue メソッドを使用する方法も示しています。The example also shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary.

このコード例は、Dictionary<TKey,TValue> クラス用に用意されている大規模な例の一部です。This code example is part of a larger example provided for the Dictionary<TKey,TValue> class. openWith は、この例で使用されるディクショナリの名前です。openWith is the name of the Dictionary used in this example.

// Create a new dictionary of strings, with string keys.
//
Dictionary<String^, String^>^ openWith =
    gcnew Dictionary<String^, String^>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add("txt", "notepad.exe");
openWith->Add("bmp", "paint.exe");
openWith->Add("dib", "paint.exe");
openWith->Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
    Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith = 
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no 
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is 
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)

' Add some elements to the dictionary. There are no 
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

' The Add method throws an exception if the new key is 
' already in the dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console::WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console::WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
// The Item property is another name for the indexer, so you 
// can omit its name when accessing elements. 
Console.WriteLine("For key = \"rtf\", value = {0}.", 
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", 
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
' The Item property is the default property, so you 
' can omit its name when accessing elements. 
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"
// 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
// 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

注釈

このプロパティは、myCollection[key] (Visual Basic でmyCollection(key)) というC#構文を使用して、コレクション内の特定の要素にアクセスする機能を提供します。This property provides the ability to access a specific element in the collection by using the following C# syntax: myCollection[key] (myCollection(key) in Visual Basic).

また、Item[TKey] プロパティを使用して、Dictionary<TKey,TValue>に存在しないキーの値を設定することによって、新しい要素を追加することもできます。You can also use the Item[TKey] property to add new elements by setting the value of a key that does not exist in the Dictionary<TKey,TValue>. プロパティ値を設定すると、キーが Dictionary<TKey,TValue>にある場合は、そのキーに関連付けられている値が割り当てられた値に置き換えられます。When you set the property value, if the key is in the Dictionary<TKey,TValue>, the value associated with that key is replaced by the assigned value. キーが Dictionary<TKey,TValue>に含まれていない場合、キーと値がディクショナリに追加されます。If the key is not in the Dictionary<TKey,TValue>, the key and value are added to the dictionary. これに対し、Add メソッドでは、既存の要素は変更されません。In contrast, the Add method does not modify existing elements.

キーを nullすることはできませんが、値の型 TValue が参照型である場合は、値をにすることができます。A key cannot be null, but a value can be, if the value type TValue is a reference type.

このC#言語では、Item[TKey] プロパティを実装する代わりに、 thisキーワードを使用してインデクサーを定義します。The C# language uses the this keyword to define the indexers instead of implementing the Item[TKey] property. Visual Basic は、Item[TKey] を既定のプロパティとして実装しており、同様のインデックス機能を提供します。Visual Basic implements Item[TKey] as a default property, which provides the same indexing functionality.

このプロパティの値を取得または設定すると、O (1) 操作に近づくことになります。Getting or setting the value of this property approaches an O(1) operation.

適用対象

こちらもご覧ください