Collection Clase
Definición
Una Collection
de Visual Basic es un conjunto ordenado de elementos a los que se puede hacer referencia como una unidad.A Visual Basic Collection
is an ordered set of items that can be referred to as a unit.
public ref class Collection sealed : System::Collections::IList
public ref class Collection sealed : System::Collections::IList, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public sealed class Collection : System.Collections.IList
[System.Serializable]
public sealed class Collection : System.Collections.IList, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Collection = class
interface ICollection
interface IEnumerable
interface IList
type Collection = class
interface ICollection
interface IList
[<System.Serializable>]
type Collection = class
interface ICollection
interface IList
interface ISerializable
interface IDeserializationCallback
Public NotInheritable Class Collection
Implements IList
Public NotInheritable Class Collection
Implements IDeserializationCallback, IList, ISerializable
- Herencia
-
Collection
- Atributos
- Implementaciones
Ejemplos
En el ejemplo siguiente se crea el Collection
objeto names
y un cuadro de diálogo con el que un usuario puede agregar objetos (nombres) a la colección.The following example creates the Collection
object names
and a dialog box with which a user can add objects (names) to the collection. A continuación, muestra los nombres de la colección y, por último, vacía la colección sin desechar el Collection
propio objeto.It then displays the names in the collection, and finally empties the collection without disposing of the Collection
object itself.
Para ver cómo funciona esto, elija el comando Agregar clase en el menú proyecto y declare una variable pública llamada instanceName
en el nivel de módulo nameClass
(tipo Public instanceName
) para contener los nombres de cada instancia.To see how this works, choose the Add Class command from the Project menu and declare a public variable called instanceName
at the module level of nameClass
(type Public instanceName
) to hold the names of each instance. Deje el nombre predeterminado como nameClass
.Leave the default name as nameClass
. Copie y pegue el código siguiente en la sección General de otro módulo y, a continuación, inícielo con la instrucción classNamer
de otro procedimiento.Copy and paste the following code into the General section of another module, and then start it with the statement classNamer
in another procedure. (Este ejemplo solo funciona con las aplicaciones host que admiten clases).(This example works only with host applications that support classes.)
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
Comentarios
Nota
Siempre que sea posible, debe usar las colecciones genéricas del System.Collections.Generic espacio de nombres o del System.Collections.Concurrent espacio de nombres en lugar de un Visual Basic Collection
.Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of a Visual Basic Collection
. Para obtener más información, vea colecciones: C# o collections-Visual Basic.For more information, see Collections - C# or Collections - Visual Basic.
El Collection
objeto Visual Basic proporciona una manera cómoda de hacer referencia a un grupo de elementos relacionado como un solo objeto.The Visual Basic Collection
object provides a convenient way to refer to a related group of items as a single object. Los elementos o elementos de una colección solo deben estar relacionados por el hecho de que existan en la colección.The items, or elements, in a collection need only be related by the fact that they exist in the collection. Los elementos de una colección no tienen que compartir el mismo tipo de datos.Elements of a collection do not have to share the same data type.
Puede crear una colección de la misma manera que crea otros objetos, como se muestra en el ejemplo siguiente.You can create a collection the same way you create other objects, as the following example illustrates.
Dim coll As New Microsoft.VisualBasic.Collection()
Una vez que haya creado una recopilación, puede realizar cualquiera de las siguientes acciones:Once you have created a collection, you can do any of the following:
Agregue un elemento con el Add método.Add an element with the Add method.
Quite un elemento con el Remove método.Remove an element with the Remove method.
Quite todos los elementos con el Clear método.Remove all elements with the Clear method.
Averigüe el número de elementos que contiene la colección con la Count propiedad.Find out how many elements the collection contains with the Count property.
Compruebe si un elemento específico está presente con el Contains método.Check whether a specific element is present with the Contains method.
Devuelve un elemento específico de la colección con la Item[] propiedad.Return a specific element from the collection with the Item[] property.
Recorrer en iteración toda la colección con la ... Instrucción siguiente.Iterate through the entire collection with the For Each...Next Statement.
Nota
Aunque el
Collection
objeto Visual Basic tiene una funcionalidad idéntica alCollection
objeto en Visual Basic 6,0, los dos no pueden interoperar en un entorno com.Although the Visual BasicCollection
object has functionality identical to theCollection
object in Visual Basic 6.0, the two cannot interoperate in a COM environment.Precaución
Recorrer en iteración un Visual Basic
Collection
no es un procedimiento seguro para subprocesos.Iterating through a Visual BasicCollection
is not a thread-safe procedure. Incluso si la colección está sincronizada, otros subprocesos aún pueden modificar la colección, lo que hace que el enumerador produzca una excepción.Even if the collection is synchronized, other threads can still modify the collection, causing the enumerator to throw an exception. Para garantizar la seguridad para subprocesos durante la enumeración, puede bloquear la colección o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.To guarantee thread safety during enumeration, either lock the collection or catch the exceptions resulting from changes made by other threads. Para obtener más información sobre el bloqueo de un elemento de programación, vea instrucción SyncLock.For more information on locking a programming element, see SyncLock Statement.
Constructores
Collection() |
Crea y devuelve un nuevo objeto Collection de Visual Basic.Creates and returns a new Visual Basic Collection object. |
Propiedades
Count |
Obtiene el número de elementos de una colección.Gets the number of elements in a collection. |
Item[Int32] |
Obtiene un elemento concreto de un objeto |
Item[Object] |
Obtiene un elemento concreto de un objeto |
Item[String] |
Obtiene un elemento concreto de un objeto |
Métodos
Add(Object, String, Object, Object) |
Agrega un elemento a un objeto |
Clear() |
Elimina todos los elementos de un objeto |
Contains(String) |
Devuelve un valor que indica si un objeto |
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual.Determines whether the specified object is equal to the current object. (Heredado de Object) |
GetEnumerator() |
Devuelve un enumerador que procesa una iteración en la colección.Returns an enumerator that iterates through the collection. |
GetHashCode() |
Sirve como la función hash predeterminada.Serves as the default hash function. (Heredado de Object) |
GetType() |
Obtiene el Type de la instancia actual.Gets the Type of the current instance. (Heredado de Object) |
MemberwiseClone() |
Crea una copia superficial del Object actual.Creates a shallow copy of the current Object. (Heredado de Object) |
Remove(Int32) |
Quita un elemento de un objeto |
Remove(String) |
Quita un elemento de un objeto |
ToString() |
Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object. (Heredado de Object) |
Implementaciones de interfaz explícitas
ICollection.CopyTo(Array, Int32) |
Copia los elementos de Collection en Array, empezando por un índice determinado de Array.Copies the elements of the Collection to an Array, starting at a particular Array index. |
ICollection.Count |
Obtiene el número de elementos de esta colección.Gets the number of items in this collection. |
ICollection.IsSynchronized |
Obtiene un valor que indica si el acceso al objeto Collection está sincronizado (es seguro para subprocesos).Gets a value that indicates whether access to the Collection object is synchronized (thread-safe). |
ICollection.SyncRoot |
Obtiene un objeto que puede utilizarse para sincronizar el acceso al objeto Collection.Gets an object that can be used to synchronize access to the Collection object. |
IDeserializationCallback.OnDeserialization(Object) |
Se ejecuta después de que se deserialice el gráfico del objeto Collection completo.Runs after the entire Collection object graph has been deserialized. |
IEnumerable.GetEnumerator() |
Obtiene un enumerador que recorre en iteración la colección.Gets an enumerator that iterates through the collection. |
IList.Add(Object) |
Agrega un elemento a la colección.Adds an item to the collection. |
IList.Clear() |
Quita todos los elementos del objeto Collection.Removes all items from the Collection object. |
IList.Contains(Object) |
Determina si el objeto Collection contiene un valor específico.Determines whether the Collection object contains a specific value. |
IList.IndexOf(Object) |
Determina el índice de un elemento específico del objeto Collection.Determines the index of a specific item in the Collection object. |
IList.Insert(Int32, Object) |
Inserta un elemento en el índice especificado del objeto Collection.Inserts an item to the Collection object at the specified index. |
IList.IsFixedSize |
Obtiene un valor que indica si el objeto Collection tiene un tamaño fijo.Gets a value that indicates whether the Collection object has a fixed size. |
IList.IsReadOnly |
Obtiene un valor que indica si el objeto Collection esGets a value that indicates whether the Collection object is. |
IList.Item[Int32] |
Obtiene o establece el elemento en el índice especificado.Gets or sets the element at the specified index. |
IList.Remove(Object) |
Quita del objeto Collection la primera aparición de un objeto específico.Removes the first occurrence of a specific object from the Collection object. |
IList.RemoveAt(Int32) |
Quita el elemento de objeto Collection del índice especificado.Removes the Collection object item at the specified index. |
ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Devuelve los datos necesarios para serializar el objeto Collection.Returns the data needed to serialize the Collection object. |
Métodos de extensión
Cast<TResult>(IEnumerable) |
Convierte los elementos de IEnumerable en el tipo especificado.Casts the elements of an IEnumerable to the specified type. |
OfType<TResult>(IEnumerable) |
Filtra los elementos de IEnumerable en función de un tipo especificado.Filters the elements of an IEnumerable based on a specified type. |
AsParallel(IEnumerable) |
Habilita la paralelización de una consulta.Enables parallelization of a query. |
AsQueryable(IEnumerable) |
Convierte una interfaz IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable. |