Collection 對象是可作為一個(gè)單元引用的一組有序項。
Collection 對象提供了一種將一組相關(guān)項作為一個(gè)對象進(jìn)行引用的便捷方法。集合中的項(或成員)只需要存在于集合中即可成為相關(guān)項。集合中的成員不需要具有相同的數據類(lèi)型。
創(chuàng )建集合的方法與創(chuàng )建其他對象相同。例如:
Dim X As New Collection
創(chuàng )建集合之后,可以使用 Add 方法添加成員,并使用 Remove 方法移除成員??梢允褂?Item 方法返回集合中的特定成員,并使用 For Each...Next 語(yǔ)句遍歷整個(gè)集合。
注意 盡管版本 6 與 .NET 中的 Collection 對象的功能相同,但它們在 COM 環(huán)境中不能交互操作。
警告 枚舉整個(gè)集合并不是線(xiàn)程安全的過(guò)程。即使集合已同步,其他線(xiàn)程仍可以修改集合,從而使枚舉數引發(fā)異常。若要確保枚舉過(guò)程中的線(xiàn)程安全性,請鎖定集合,或者捕獲由其他線(xiàn)程做出的更改所導致的異常。
本示例創(chuàng )建一個(gè) Collection 對象 (MyClasses),并創(chuàng )建了用戶(hù)可以在其中向集合添加對象的對話(huà)框。若要查看其運行效果,請從“項目”菜單中選擇“類(lèi)”命令,并在 Class1 的模塊級聲明一個(gè)名為 InstanceName 的公共變量(鍵入 Public InstanceName)以保存每個(gè)實(shí)例的名稱(chēng)。請保留默認名稱(chēng) Class1。將下列代碼復制并粘貼到另一個(gè)模塊的“常規”部分,然后在另一個(gè)過(guò)程中用語(yǔ)句 ClassNamer 啟動(dòng)它。(本示例僅能用支持類(lèi)的宿主應用程序運行。)
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聯(lián)系客服