Hashtable.Item[Object] 屬性

定義

取得或設定與指定之索引鍵相關聯的值。

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

參數

key
Object

索引鍵,要讀取或設定其值。

屬性值

與指定之索引鍵關聯的值。 如果找不到指定的索引鍵,嘗試取得將傳回 null,並且嘗試設定會使用指定的索引鍵建立新的元素。

實作

例外狀況

keynull

屬性已設定,而且 Hashtable 是唯讀的。

-或-

屬性已設定、key 不在於集合中,而且 Hashtable 的大小固定。

備註

這個屬性可透過下列語法存取集合中的特定元素:myCollection[key]

您也可以使用 Item[] 屬性來新增專案,方法是設定不存在於 中的Hashtable索引鍵值,例如 。 myCollection["myNonexistentKey"] = myValue 不過,如果指定的索引鍵已存在於 中 Hashtable,則設定 Item[] 屬性會覆寫舊的值。 相反地, Add 方法不會修改現有的專案。

索引鍵不能是 null,但值可以是 。 若要區分 null 傳回的 ,因為找不到指定的索引鍵,而且 null 因為指定索引鍵的值是 null傳回,請使用 Contains 方法或 ContainsKey 方法來判斷索引鍵是否存在於清單中。

擷取這個屬性的值是 O(1) 作業;設定屬性也是 O(1) 作業。

C# 語言使用 this 關鍵字定義索引,而不必實作 Item[] 屬性。 Visual Basic 會將 Item[] 實作為預設屬性,這樣會提供相同的索引功能。

適用於

另請參閱