使用集合替代数组

更新:2007 年 11 月

尽管集合一般是用来处理 Object 数据类型的,但它也可以用来处理任何数据类型。有时用集合存取数据比用数组更加有效。

如果需要更改数组的大小,必须使用 ReDim 语句 (Visual Basic)。当您这样做时,Visual Basic 会创建一个新数组并释放以前的数组以便处置。这需要一定的执行时间。因此,如果您处理的项数经常更改,或者您无法预测所需的最大项数,则可以使用集合来获得更好的性能。

集合不用创建新对象或复制现有元素,它在处理大小调整时所用的执行时间比数组少,而数组必须使用 ReDim。但是,如果不更改或很少更改大小,数组很可能更有效。一直以来,性能在很大程度上都依赖于个别的应用程序。您应该花时间把数组和集合都尝试一下。

专用集合

.NET Framework 还提供了各种用于常规集合和特殊集合的类、接口和结构。System.CollectionsSystem.Collections.Specialized 命名空间包含定义和实现,定义和实现又包括字典、列表、队列和堆栈。System.Collections.Generic 命名空间提供其中许多泛型版本,它们又具有一个或多个类型参数。

如果集合中只包含具有一种特定数据类型的元素,泛型集合在强制“类型安全”方面具有优势。有关泛型的更多信息,请参见 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 循环来遍历集合并显示集合的元素。

请参见

任务

如何:声明数组变量

如何:创建数组

如何:初始化数组变量

数组疑难解答

概念

Visual Basic 中的集合

Visual Basic 中的泛型类型

参考

ReDim 语句 (Visual Basic)

其他资源

数组 (Visual Basic)