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) 指定集合的元素位置的数值表达式。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 对象的默认属性。

要求

命名空间:Microsoft.VisualBasic

**模块:**Collection

**程序集:**Visual Basic 运行库(在 Microsoft.VisualBasic.dll 中)

请参见

参考

Collection 对象 (Visual Basic)

Add 方法(Collection 对象)

Count 属性(Collection 对象)

Remove 方法(Collection 对象)