Collection 物件 (Visual Basic)
更新:2007 年 11 月
Visual Basic Collection 是一組已排序的項目,可以稱為一個單位。
備註
Visual Basic Collection 物件提供了非常方便的方式,可將一組相關的項目視為單一物件。集合物件中的「項目」(Element) 只需依照它們所在的集合相關聯。集合的項目不必共用相同的資料型別。
建立集合的方式與建立其他物件的方式相同 (如下列範例所述)。
Dim coll As New Microsoft.VisualBasic.Collection()
建立集合後,即可執行下列其中一項作業:
加入使用 Add 方法的項目。
移除使用 Remove 方法的項目。
移除所有使用 Clear 方法的項目。
使用 Count 屬性找到集合中所含的項目數。
使用 Contains 方法檢查特定項目是否存在。
使用 Item 屬性傳回集合中的特定項目。
使用 For Each...Next 陳述式 (Visual Basic) 逐一查看整個集合。
注意事項: 雖然 Visual Basic Collection 物件與 Visual Basic 6.0 中 Collection 物件的功能完全相同,但這兩個物件無法在 COM 環境中相互溝通。
警告: 逐一查看 Visual Basic Collection 並不是安全執行緒的程序。即使集合同步化時,其他執行緒仍然可以修改集合。這會導致列舉值擲回例外狀況。若要保證列舉過程的執行緒安全,您可以在整個列舉過程中鎖定集合,或攔截因其他執行緒的變更所造成的例外狀況。如需鎖定程式設計項目的詳細資訊,請參閱 SyncLock 陳述式。
範例
下列範例會建立 Collection 物件 names 和對話方塊,使用者可用於將物件 (名稱) 加入至集合中。然後,它會在集合中顯示名稱,且於最後清空集合,而不處置 Collection 物件本身。
若要了解其中的運作方式,請選取 [專案] 功能表中的 [加入類別] 命令,然後在 nameClass (Public instanceName 型別) 的模組層次宣告名為 instanceName 的公用變數,來儲存每一個執行個體的名稱。請將預設名稱保留為 nameClass。複製下列程式碼並貼到另一個模組的 [一般] 區段中,然後以其他程序中的 classNamer 陳述式來啟動程式碼 (此範例只適用於支援類別的主應用程式)。
Public Class nameClass
Public instanceName As String
End Class
Sub classNamer()
' Create a Visual Basic Collection object.
Dim names As New Microsoft.VisualBasic.Collection()
Dim key As Integer
Dim msg As String
Dim name As String
Dim nameList As String = ""
' 1. Get names from the user to add to the collection.
Do
Dim inst As New nameClass()
key += 1
msg = "Please enter a name for this object." & vbCrLf _
& "Press Cancel to see names in collection."
name = InputBox(msg, "Name the Collection items")
inst.instanceName = name
' If user entered a name, add it to the collection.
If inst.instanceName <> "" Then
names.Add(inst, CStr(key))
End If
Loop Until name = ""
' 2. Create and display a list of names from the collection.
For Each oneInst As nameClass In names
nameList &= oneInst.instanceName & vbCrLf
Next oneInst
MsgBox(nameList, , "Instance Names in names Collection")
' 3. Remove elements from the collection without disposing of the collection.
For count As Integer = 1 To names.Count
names.Remove(1)
' Since Visual Basic collections are reindexed automatically,
' remove the first member on each iteration.
Next count
End Sub
需求
組件:Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)