PropertyCollection.IDictionary.Item[Object] プロパティ

定義

指定したキーを持つ要素を取得または設定します。

property System::Object ^ System::Collections::IDictionary::Item[System::Object ^] { System::Object ^ get(System::Object ^ key); void set(System::Object ^ key, System::Object ^ value); };
object System.Collections.IDictionary.Item[object key] { get; set; }
member this.System.Collections.IDictionary.Item(obj) : obj with get, set
 Property Item(key As Object) As Object Implements IDictionary.Item

パラメーター

key
Object

取得または設定する要素のキー。

プロパティ値

指定したキーを持つ要素。

実装

例外

keynullです。

プロパティが設定され、 IDictionary オブジェクトは読み取り専用です。

-または-

プロパティが設定され、 key がコレクションに存在せず、 IDictionary のサイズが固定されています。

次の例は、 Item[] プロパティを実装する方法を示しています。 このコード例は、 IDictionary クラスに提供されるより大きな例の一部です。

public object this[object key]
{
    get
    {
        // If this key is in the dictionary, return its value.
        Int32 index;
        if (TryGetIndexOfKey(key, out index))
        {
            // The key was found; return its value.
            return items[index].Value;
        }
        else
        {
            // The key was not found; return null.
            return null;
        }
    }

    set
    {
        // If this key is in the dictionary, change its value.
        Int32 index;
        if (TryGetIndexOfKey(key, out index))
        {
            // The key was found; change its value.
            items[index].Value = value;
        }
        else
        {
            // This key is not in the dictionary; add this key/value pair.
            Add(key, value);
        }
    }
}
Public Property Item(ByVal key As Object) As Object Implements IDictionary.Item
    Get

        ' If this key is in the dictionary, return its value.
        Dim index As Integer
        If TryGetIndexOfKey(key, index) Then

            ' The key was found return its value.
            Return items(index).Value
        Else

            ' The key was not found return null.
            Return Nothing
        End If
    End Get

    Set(ByVal value As Object)
        ' If this key is in the dictionary, change its value. 
        Dim index As Integer
        If TryGetIndexOfKey(key, index) Then

            ' The key was found change its value.
            items(index).Value = value
        Else

            ' This key is not in the dictionary add this key/value pair.
            Add(key, value)
        End If
    End Set
End Property

注釈

このプロパティは、次の構文を使用してコレクション内の特定の要素にアクセスする機能を提供します: myCollection[key]

Item[] プロパティを使用して、ディクショナリに存在しないキーの値 (たとえば、myCollection["myNonexistentKey"] = myValue) を設定して、新しい要素を追加することもできます。 ただし、指定したキーがディクショナリに既に存在する場合は、 Item[] プロパティを設定すると、古い値が上書きされます。 これに対し、 Add メソッドは既存の要素を変更しません。

適用対象

こちらもご覧ください