Collection 对象

来源:百度文库 编辑:神马文学网 时间:2024/06/12 12:46:51
Collection 对象

Collection 对象是可作为一个单元引用的一组有序项。

备注

Collection 对象提供了一种将一组相关项作为一个对象进行引用的便捷方法。集合中的项(或成员)只需要存在于集合中即可成为相关项。集合中的成员不需要具有相同的数据类型。

创建集合的方法与创建其他对象相同。例如:

复制代码
Dim X As New Collection

创建集合之后,可以使用 Add 方法添加成员,并使用 Remove 方法移除成员。可以使用 Item 方法返回集合中的特定成员,并使用 For Each...Next 语句遍历整个集合。

注意   尽管版本 6 与 .NET 中的 Collection 对象的功能相同,但它们在 COM 环境中不能交互操作。
警告   枚举整个集合并不是线程安全的过程。即使集合已同步,其他线程仍可以修改集合,从而使枚举数引发异常。若要确保枚举过程中的线程安全性,请锁定集合,或者捕获由其他线程做出的更改所导致的异常。

示例

本示例创建一个 Collection 对象 (MyClasses),并创建了用户可以在其中向集合添加对象的对话框。若要查看其运行效果,请从“项目”菜单中选择“类”命令,并在 Class1 的模块级声明一个名为 InstanceName 的公共变量(键入 Public InstanceName)以保存每个实例的名称。请保留默认名称 Class1。将下列代码复制并粘贴到另一个模块的“常规”部分,然后在另一个过程中用语句 ClassNamer 启动它。(本示例仅能用支持类的宿主应用程序运行。)

复制代码
Public Class Class1Public InstanceName As StringEnd ClassSub ClassNamer()Dim MyClasses As New Collection()   ' Create a Collection object.Dim number As Integer   ' Counter for individualizing keys.Dim Msg As String   ' Variable to hold prompt string.Dim name As StringDim oneInst As Class1Dim nameList As String = ""DoDim inst As New Class1()   ' Create a new instance of Class1.number += 1   ' Increment Num, then get a name.Msg = "Please enter a name for this object." & ControlChars.CrLf _& "Press Cancel to see names in collection."name = InputBox(Msg, "Name the Collection Items")Inst.InstanceName = name   ' Put name in object instance.' If user entered name, add it to the collection.If inst.InstanceName <> "" Then' Add the named object to the collection.MyClasses.Add (inst, number.ToString())End IfLoop Until name = ""For Each oneInst In MyClasses   ' Create list of names.nameList &= oneInst.InstanceName & ControlChars.CrLfNext' Display the list of names in a message box.MsgBox (nameList, , "Instance Names In MyClasses Collection")Dim count As IntegerFor count = 1 To MyClasses.Count' Remove name from the collection.MyClasses.Remove(1)' Since collections are reindexed automatically, remove' the first member on each iterationNextEnd Sub