Compartilhar via


Coleção de Classes do Visual Basic

A collection is a way of grouping a set of related items. Many different types of collections exist. Predefined collections are used in Visual Basic applications for many purposes, for example the Control.ControlCollection on a Form, returned by the form's Controls property. You can also create your own collections to organize and manipulate objects.

Collections are a good way to keep track of objects that your application might need to dynamically create and destroy. O fragmento de código a seguir mostra como você pode usar o Addométodo de um Visual Basic Collectionoobjeto para manter uma lista de  widget objetos que o usuário criou.

' Declare and create the Collection object.
Public widgetColl As New Microsoft.VisualBasic.Collection() 
' Create a new widget and add it to the widgetColl collection.
Private Sub makeAWidget()
    Dim tempWidget As New widget()
    widgetColl.Add(tempWidget) 
End Sub

In the preceding example, the widgetColl collection organizes and exposes all of the widget objects created through the makeAWidget procedure. You can retrieve object references to each widget through the index of the collection. The size of the collection is adjusted automatically as each new widget object is added. You can use the Instrução For Each...Next (Visual Basic) to iterate through the collection. If you want to give the widget object a key by which it can be retrieved, you can supply a text string as the second parameter of the Add method.

O Visual Basic Collection objeto armazena todos os seus elementos, como o tipo de Object, portanto, você pode adicionar um item de qualquer tipo de dados. There is no safeguard against inappropriate data types being added. To avoid this limitation, you can use the generic collections of the System.Collections.Generic namespace. For more information, see Como: Criar uma coleção de objetos (Visual Basic).

Creating and Destroying a Collection Object

The operador New (Visual Basic) keyword in the declaration for the variable widgetColl causes a Collection object to be created when control passes to the declaration statement. Because Collection is a class, rather than a value type, you must create an instance of it and keep a reference to that instance in a variable. Esta instância é um Visual Basic Collectiondeobjeto. 

Like any other object, a Collection object is marked for garbage collection (GC) when the last variable that contains a reference to it is set to Nada (Visual Basic) or goes out of scope. All the object references it contains are released when it is reclaimed by garbage collection. For this reason, the variable widgetColl in the preceding example is declared in the parent class, so that it exists throughout the life of the program.

A collection maintains references to the objects it controls but does not contain the objects themselves. Therefore, destroying a Collection object does not destroy the objects it controls. Each individual object that had been an element of the collection continues to exist until it is individually marked for garbage collection.

Working with Elements

The basic services of adding, deleting, and retrieving elements from a collection depend on keys and indexes. A key is a String value. It could be a name, a driver's license number, a phone number, or simply an integer converted to a string. The Add method allows you to associate a key with an element, as described in Como: adicionar, excluir e recuperar itens de uma coleção (Visual Basic).

An index in the Collection class is an integer between 1 and the number of items in the collection. O Count propriedade retorna o número atual de itens. You can control the initial value of an item's index by using the Before or After parameters when you call Add, but the index value could change as other items are added and deleted. For more information, see Add.

Você pode remover um único elemento de uma coleção , passando a sua chave ou em seu índice para o Remove método. Você pode esvaziar uma coleção e remover todos os elementos com o Clear método.

Accessing Elements

Você pode passar um valor de chave para o Contains método para teste se uma coleção contém um elemento com essa chave. Você pode recuperar um elemento, passando a sua chave ou em seu índice para o Item propriedade.

You can use index values and the Item property to iterate over the items in a collection, or you can use the Instrução For Each...Next (Visual Basic). The following example shows two ways to give all the employees in a collection of employee objects a 10 percent raise, assuming that the variable employeesColl contains a reference to a Collection object.

Option Strict On
' The following alternative uses the Count and Item properties.
Dim emp As employee
For counter As Integer = 1 To employeesColl.Count 
    emp = CType(employeesColl.Item(counter), employee)
    emp.payRate *= 1.1
Next counter
' The following alternative uses the For Each...Next statements.
For Each emp As employee In employeesColl
    emp.payRate *= 1.1
Next emp

However, if you have added one or more elements to employeesColl that are not of type employee, the For Each loop throws an ArgumentException exception at run time.

Data Type of Elements

A Visual Basic Collection objeto armazena cada item com tipo de dados Object. Therefore, the range of data types you can add to a Collection object is the same as the range of data types you can store in an Object variable. This includes standard data types, objects, and arrays, as well as user-defined structures and class instances.

Because the Collection object stores each item as an Object, the Item property returns an Object value. To use the item in your code, you must typically convert from Object to the run-time data type of the item. The way you do this depends on the setting of the type checking switch in the Opção declaração estrito.

Implicitly Converting from Object

If Option Strict is Off, you can implicitly convert an element of the Collection to its appropriate data type, as shown in the following example.

Option Strict Off
Dim sampleColl As New Microsoft.VisualBasic.Collection()
Dim sampleString As String = "This is a string"
Dim aString As String
sampleColl.Add(sampleString)
' The following statements convert the collection item to a string.
Try
    aString = sampleColl.Item(1) 
Catch ex As Exception
    ' Insert code to run if the collection item cannot be converted to String.
End Try

Explicitly Converting from Object

If Option Strict is On, you must explicitly convert from Object to the run-time data type of the element. To obtain an element from Item in this way, you can use the Função CType (Visual Basic) to perform the conversion, as shown in the following example.

Option Strict On
Dim sampleColl As New Microsoft.VisualBasic.Collection()
Dim sampleString As String = "This is a string"
Dim aString As String
sampleColl.Add(sampleString)
' The following statements convert the collection item to a string.
Try
    aString = CType(sampleColl.Item(1), String) 
Catch ex As Exception
    ' Insert code to run if the collection item cannot be converted to String.
End Try

Additional Services

The properties and methods of the Collection object provide only the most basic services for collections. For example, the Add method cannot check the type of an element being added to a collection, which you might want to do to ensure that the collection contains only one kind of element. If you can ensure this in the Add method, you have a strongly-typed collection, and you do not have to convert the return from the Item property to its run-time data type. This improves your performance.

You can provide more robust functionality — and additional properties, methods, and events — by creating your own collection class, as described in Como: Definir coleções nas suas classes (Visual Basic).

Consulte também

Referência

Collection

Conceitos

Matrizes no Visual Basic

Coleções em Visual Basic