語言

IDictionary.Item[Object] 屬性

定義

取得或設定具有指定索引鍵的專案。

public:
 property System::Object ^ default[System::Object ^] { System::Object ^ get(System::Object ^ key); void set(System::Object ^ key, System::Object ^ value); };
public object this[object key] { get; set; }
public object? this[object key] { get; set; }
member this.Item(obj) : obj with get, set
Default Public Property Item(key As Object) As Object

參數

key
Object

關鍵是要取得或設定。

屬性值

該元素包含指定鍵,或 null 若鍵不存在。

例外狀況

key 是 null。

屬性已設定,物件 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 方法不會修改現有元素。

實作中是否允許 key 為 null。

C# 語言使用 thisthis 關鍵字來定義索引器,而非實作該 Item[] 屬性。 Visual Basic 作為 Item[] 預設屬性實作,提供相同的索引功能。

適用於

另請參閱