Share via


Item 屬性 (Collection 物件)

更新:2007 年 11 月

依位置或索引鍵傳回 Collection 物件的特定成員。唯讀。

Default Public ReadOnly Property Item( _
    ByVal { Key As String | Index As Integer | Index As Object } _
) As Object

參數

  • Key
    唯一的 String 運算式,指定可用來存取集合項目的索引鍵字串,藉以取代位置索引。Key 必須對應至當項目加入至集合時所指定的 Key 引數。

  • Index
    (A) 數值運算式 (Numeric Expression),可指定集合中項目的位置。Index 必須是介於 1 到集合的 Count 屬性 (Collection 物件) 值之間的數字。或 (B) Object 運算式,指定集合項目的位置或索引鍵字串。

例外狀況

例外狀況類型

錯誤代碼

條件

ArgumentException

5

  • Key 無效,或不與集合的任何現有項目相符。

  • Index 無法解譯為字元或數值資料。

IndexOutOfRangeException

9

  • Key 為 Nothing。

  • Index 不與集合的任何現有項目相符。

如果將使用非結構化錯誤處理的 Visual Basic 6.0 應用程式升級,請參閱「錯誤代碼」資料行 (您可以將錯誤代碼與 Number 屬性 (Err 物件) 比對)。但是,請盡可能考慮以 Visual Basic 的結構化例外處理概觀 取代這類錯誤控制項。

備註

如果 Index 屬於 Object 型別,則 Item 屬性會嘗試將它當做 String、Char、Char 陣列或整數值來處理。如果 Item 無法將 Index 轉換為 String 或 Integer,則會擲回 ArgumentException 例外狀況。

Item 屬性是集合物件的預設屬性。因此,下列兩行程式碼是一樣的。

MsgBox(CStr(customers.Item(1)))
MsgBox(CStr(customers(1)))

範例

下列範例將使用 Item 屬性來擷取集合物件中的物件參考。它會將 birthdays 建立為 Collection 物件,物件,然後擷取表示 Bill 生日的物件 (透過的方式是將索引鍵 "Bill" 當做 Index 引數使用)。

Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")


...


Dim aBirthday As DateTime
aBirthday = birthdays.Item("Bill")
MsgBox(CStr(aBirthday))
aBirthday = birthdays("Bill")
MsgBox(CStr(aBirthday))

請注意,第一次的呼叫會明確指定 Item 屬性,但第二次則否。不過這兩次呼叫都可運作,這是因為 Item 屬性是 Collection 物件的預設屬性。

需求

命名空間 (Namespace)︰Microsoft.VisualBasic

**模組︰**Collection

組件 (Assembly):Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

Collection 物件 (Visual Basic)

Add 方法 (集合物件)

Count 屬性 (Collection 物件)

Remove 方法 (Collection 物件)