使用集合取代陣列
更新:2007 年 11 月
雖然集合最常和Object 資料型別一起使用,但是您也可以將集合搭配任何資料型別使用。在某些情況下,將項目儲存在集合中可能比儲存在陣列中更有效。
如果必須變更陣列的大小,請務必使用 ReDim 陳述式 (Visual Basic)。當您這麼做時,Visual Basic 會建立新的陣列,並釋出先前的陣列以供處置 (Dispose)。這將佔用執行時間。因此,如果您處理的項目數經常變更,或無法預測需要的最大項目數,您可以使用集合來達到較佳的效能。
集合不需要建立新的物件或複製現有項目,調整大小的執行時間也比陣列 (需使用 ReDim) 短。但如果大小不變或極少變動,使用陣列可能較有效率。一如往常,效能大多取決於個別應用程式。所以不妨試著同時使用陣列和集合。
特殊化集合
.NET Framework 也提供多種類別、介面及結構,以供一般及特殊集合使用。System.Collections 和 System.Collections.Specialized 命名空間包含定義及實作,其中又包括了字典、清單、佇列及堆疊。System.Collections.Generic 命名空間提供了許多泛型版本,而這些版本需要一或多個的型別引數。
如果您的集合只用於存放一種特殊資料型別的項目,使用泛型集合可幫助加強「型別安全 (Type Safety)」。如需泛型的詳細資訊,請參閱 Visual Basic 中的泛型型別。
範例
描述
以下範例使用 .NET Framework 泛型類別 System.Collections.Generic.List<T> 來建立 customer 結構之清單集合。
程式碼
' Define the structure for a customer.
Public Structure customer
Public name As String
' Insert code for other members of customer structure.
End Structure
' Create a module-level collection that can hold 200 elements.
Public custFile As New List(Of customer)(200)
' Add a specified customer to the collection.
Private Sub addNewCustomer(ByVal newCust As customer)
' Insert code to perform validity check on newCust.
custFile.Add(newCust)
End Sub
' Display the list of customers in the Debug window.
Private Sub printCustomers()
For Each cust As customer In custFile
Debug.WriteLine(cust)
Next cust
End Sub
註解
custFile 集合的宣告指定它僅可包含型別 customer 的項目。同時也提供 200 個項目的初始容量。程序 addNewCustomer 會檢查新項目的有效性,然後將它加入集合中。程序 printCustomers 會使用 For Each 迴圈以便穿越集合並顯示項目。