CollectionBase Clase

Definición

Proporciona la clase base abstract para una colección fuertemente tipada.Provides the abstract base class for a strongly typed collection.

public ref class CollectionBase abstract : System::Collections::IList
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class CollectionBase : System.Collections.IList
type CollectionBase = class
    interface IList
    interface ICollection
    interface IEnumerable
Public MustInherit Class CollectionBase
Implements IList
Herencia
CollectionBase
Derivado
Atributos
Implementaciones

Ejemplos

En el ejemplo de código siguiente se implementa la clase CollectionBase y se utiliza esa implementación para crear una colección de objetos Int16.The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects.

#using <System.dll>

using namespace System;
using namespace System::Collections;

public ref class Int16Collection: public CollectionBase
{
public:

   property Int16 Item [int]
   {
      Int16 get( int index )
      {
         return ( (Int16)(List[ index ]));
      }

      void set( int index, Int16 value )
      {
         List[ index ] = value;
      }
   }
   int Add( Int16 value )
   {
      return (List->Add( value ));
   }

   int IndexOf( Int16 value )
   {
      return (List->IndexOf( value ));
   }

   void Insert( int index, Int16 value )
   {
      List->Insert( index, value );
   }

   void Remove( Int16 value )
   {
      List->Remove( value );
   }

   bool Contains( Int16 value )
   {
      // If value is not of type Int16, this will return false.
      return (List->Contains( value ));
   }

protected:
   virtual void OnInsert( int /*index*/, Object^ /*value*/ ) override
   {
      // Insert additional code to be run only when inserting values.
   }

   virtual void OnRemove( int /*index*/, Object^ /*value*/ ) override
   {
      // Insert additional code to be run only when removing values.
   }

   virtual void OnSet( int /*index*/, Object^ /*oldValue*/, Object^ /*newValue*/ ) override
   {
      // Insert additional code to be run only when setting values.
   }

   virtual void OnValidate( Object^ value ) override
   {
      if ( value->GetType() != Type::GetType( "System.Int16" ) )
            throw gcnew ArgumentException( "value must be of type Int16.","value" );
   }

};

void PrintIndexAndValues( Int16Collection^ myCol );
void PrintValues2( Int16Collection^ myCol );
int main()
{
   // Create and initialize a new CollectionBase.
   Int16Collection^ myI16 = gcnew Int16Collection;
   
   // Add elements to the collection.
   myI16->Add( (Int16)1 );
   myI16->Add( (Int16)2 );
   myI16->Add( (Int16)3 );
   myI16->Add( (Int16)5 );
   myI16->Add( (Int16)7 );

   // Display the contents of the collection using the enumerator.
   Console::WriteLine( "Contents of the collection (using enumerator):" );
   PrintValues2( myI16 );

   // Display the contents of the collection using the Count property and the Item property.
   Console::WriteLine( "Initial contents of the collection (using Count and Item):" );
   PrintIndexAndValues( myI16 );

   // Search the collection with Contains and IndexOf.
   Console::WriteLine( "Contains 3: {0}", myI16->Contains( 3 ) );
   Console::WriteLine( "2 is at index {0}.", myI16->IndexOf( 2 ) );
   Console::WriteLine();

   // Insert an element into the collection at index 3.
   myI16->Insert( 3, (Int16)13 );
   Console::WriteLine( "Contents of the collection after inserting at index 3:" );
   PrintIndexAndValues( myI16 );

   // Get and set an element using the index.
   myI16->Item[ 4 ] = 123;
   Console::WriteLine( "Contents of the collection after setting the element at index 4 to 123:" );
   PrintIndexAndValues( myI16 );

   // Remove an element from the collection.
   myI16->Remove( (Int16)2 );

   // Display the contents of the collection using the Count property and the Item property.
   Console::WriteLine( "Contents of the collection after removing the element 2:" );
   PrintIndexAndValues( myI16 );
}

// Uses the Count property and the Item property.
void PrintIndexAndValues( Int16Collection^ myCol )
{
   for ( int i = 0; i < myCol->Count; i++ )
      Console::WriteLine( "   [{0}]:   {1}", i, myCol->Item[ i ] );
   Console::WriteLine();
}

// Uses the enumerator. 
void PrintValues2( Int16Collection^ myCol )
{
   System::Collections::IEnumerator^ myEnumerator = myCol->GetEnumerator();
   while ( myEnumerator->MoveNext() )
      Console::WriteLine( "   {0}", myEnumerator->Current );

   Console::WriteLine();
}

/* 
This code produces the following output.

Contents of the collection (using enumerator):
   1
   2
   3
   5
   7

Initial contents of the collection (using Count and Item):
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   5
   [4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   5
   [5]:   7

Contents of the collection after setting the element at index 4 to 123:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   123
   [5]:   7

Contents of the collection after removing the element 2:
   [0]:   1
   [1]:   3
   [2]:   13
   [3]:   123
   [4]:   7

*/
using System;
using System.Collections;

public class Int16Collection : CollectionBase  {

   public Int16 this[ int index ]  {
      get  {
         return( (Int16) List[index] );
      }
      set  {
         List[index] = value;
      }
   }

   public int Add( Int16 value )  {
      return( List.Add( value ) );
   }

   public int IndexOf( Int16 value )  {
      return( List.IndexOf( value ) );
   }

   public void Insert( int index, Int16 value )  {
      List.Insert( index, value );
   }

   public void Remove( Int16 value )  {
      List.Remove( value );
   }

   public bool Contains( Int16 value )  {
      // If value is not of type Int16, this will return false.
      return( List.Contains( value ) );
   }

   protected override void OnInsert( int index, Object value )  {
      // Insert additional code to be run only when inserting values.
   }

   protected override void OnRemove( int index, Object value )  {
      // Insert additional code to be run only when removing values.
   }

   protected override void OnSet( int index, Object oldValue, Object newValue )  {
      // Insert additional code to be run only when setting values.
   }

   protected override void OnValidate( Object value )  {
      if ( value.GetType() != typeof(System.Int16) )
         throw new ArgumentException( "value must be of type Int16.", "value" );
   }

}


public class SamplesCollectionBase  {

   public static void Main()  {
 
      // Create and initialize a new CollectionBase.
      Int16Collection myI16 = new Int16Collection();

      // Add elements to the collection.
      myI16.Add( (Int16) 1 );
      myI16.Add( (Int16) 2 );
      myI16.Add( (Int16) 3 );
      myI16.Add( (Int16) 5 );
      myI16.Add( (Int16) 7 );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Contents of the collection (using foreach):" );
      PrintValues1( myI16 );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Contents of the collection (using enumerator):" );
      PrintValues2( myI16 );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Initial contents of the collection (using Count and Item):" );
      PrintIndexAndValues( myI16 );

      // Search the collection with Contains and IndexOf.
      Console.WriteLine( "Contains 3: {0}", myI16.Contains( 3 ) );
      Console.WriteLine( "2 is at index {0}.", myI16.IndexOf( 2 ) );
      Console.WriteLine();

      // Insert an element into the collection at index 3.
      myI16.Insert( 3, (Int16) 13 );
      Console.WriteLine( "Contents of the collection after inserting at index 3:" );
      PrintIndexAndValues( myI16 );

      // Get and set an element using the index.
      myI16[4] = 123;
      Console.WriteLine( "Contents of the collection after setting the element at index 4 to 123:" );
      PrintIndexAndValues( myI16 );

      // Remove an element from the collection.
      myI16.Remove( (Int16) 2 );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Contents of the collection after removing the element 2:" );
      PrintIndexAndValues( myI16 );

   }
 
   // Uses the Count property and the Item property.
   public static void PrintIndexAndValues( Int16Collection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   [{0}]:   {1}", i, myCol[i] );
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues1( Int16Collection myCol )  {
      foreach ( Int16 i16 in myCol )
         Console.WriteLine( "   {0}", i16 );
      Console.WriteLine();
   }

   // Uses the enumerator. 
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues2( Int16Collection myCol )  {
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0}", myEnumerator.Current );
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

Contents of the collection (using foreach):
   1
   2
   3
   5
   7

Contents of the collection (using enumerator):
   1
   2
   3
   5
   7

Initial contents of the collection (using Count and Item):
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   5
   [4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   5
   [5]:   7

Contents of the collection after setting the element at index 4 to 123:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   123
   [5]:   7

Contents of the collection after removing the element 2:
   [0]:   1
   [1]:   3
   [2]:   13
   [3]:   123
   [4]:   7

*/

Imports System.Collections


Public Class Int16Collection
   Inherits CollectionBase


   Default Public Property Item(index As Integer) As Int16
      Get
         Return CType(List(index), Int16)
      End Get
      Set
         List(index) = value
      End Set
   End Property


   Public Function Add(value As Int16) As Integer
      Return List.Add(value)
   End Function 'Add

   Public Function IndexOf(value As Int16) As Integer
      Return List.IndexOf(value)
   End Function 'IndexOf


   Public Sub Insert(index As Integer, value As Int16)
      List.Insert(index, value)
   End Sub


   Public Sub Remove(value As Int16)
      List.Remove(value)
   End Sub


   Public Function Contains(value As Int16) As Boolean
      ' If value is not of type Int16, this will return false.
      Return List.Contains(value)
   End Function 'Contains


   Protected Overrides Sub OnInsert(index As Integer, value As Object)
      ' Insert additional code to be run only when inserting values.
   End Sub


   Protected Overrides Sub OnRemove(index As Integer, value As Object)
      ' Insert additional code to be run only when removing values.
   End Sub


   Protected Overrides Sub OnSet(index As Integer, oldValue As Object, newValue As Object)
      ' Insert additional code to be run only when setting values.
   End Sub


   Protected Overrides Sub OnValidate(value As Object)
      If Not GetType(System.Int16).IsAssignableFrom(value.GetType()) Then
         Throw New ArgumentException("value must be of type Int16.", "value")
      End If
   End Sub

End Class


Public Class SamplesCollectionBase

   Public Shared Sub Main()

      ' Creates and initializes a new CollectionBase.
      Dim myI16 As New Int16Collection()

      ' Adds elements to the collection.
      myI16.Add( 1 )
      myI16.Add( 2 )
      myI16.Add( 3 )
      myI16.Add( 5 )
      myI16.Add( 7 )

      ' Display the contents of the collection using For Each. This is the preferred method.
      Console.WriteLine("Contents of the collection (using For Each):")
      PrintValues1(myI16)
      
      ' Display the contents of the collection using the enumerator.
      Console.WriteLine("Contents of the collection (using enumerator):")
      PrintValues2(myI16)
      
      ' Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine("Initial contents of the collection (using Count and Item):")
      PrintIndexAndValues(myI16)
      
      ' Searches the collection with Contains and IndexOf.
      Console.WriteLine("Contains 3: {0}", myI16.Contains(3))
      Console.WriteLine("2 is at index {0}.", myI16.IndexOf(2))
      Console.WriteLine()
      
      ' Inserts an element into the collection at index 3.
      myI16.Insert(3, 13)
      Console.WriteLine("Contents of the collection after inserting at index 3:")
      PrintIndexAndValues(myI16)
      
      ' Gets and sets an element using the index.
      myI16(4) = 123
      Console.WriteLine("Contents of the collection after setting the element at index 4 to 123:")
      PrintIndexAndValues(myI16)
      
      ' Removes an element from the collection.
      myI16.Remove(2)

      ' Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine("Contents of the collection after removing the element 2:")
      PrintIndexAndValues(myI16)

    End Sub


    ' Uses the Count property and the Item property.
    Public Shared Sub PrintIndexAndValues(myCol As Int16Collection)
      Dim i As Integer
      For i = 0 To myCol.Count - 1
          Console.WriteLine("   [{0}]:   {1}", i, myCol(i))
      Next i
      Console.WriteLine()
    End Sub


    ' Uses the For Each statement which hides the complexity of the enumerator.
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues1(myCol As Int16Collection)
      Dim i16 As Int16
      For Each i16 In  myCol
          Console.WriteLine("   {0}", i16)
      Next i16
      Console.WriteLine()
    End Sub


    ' Uses the enumerator. 
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues2(myCol As Int16Collection)
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
          Console.WriteLine("   {0}", myEnumerator.Current)
      End While
      Console.WriteLine()
    End Sub

End Class


'This code produces the following output.
'
'Contents of the collection (using For Each):
'   1
'   2
'   3
'   5
'   7
'
'Contents of the collection (using enumerator):
'   1
'   2
'   3
'   5
'   7
'
'Initial contents of the collection (using Count and Item):
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   5
'   [4]:   7
'
'Contains 3: True
'2 is at index 1.
'
'Contents of the collection after inserting at index 3:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   13
'   [4]:   5
'   [5]:   7
'
'Contents of the collection after setting the element at index 4 to 123:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   13
'   [4]:   123
'   [5]:   7
'
'Contents of the collection after removing the element 2:
'   [0]:   1
'   [1]:   3
'   [2]:   13
'   [3]:   123
'   [4]:   7

Comentarios

Importante

No se recomienda usar la clase CollectionBase para el desarrollo nuevo.We don't recommend that you use the CollectionBase class for new development. En su lugar, se recomienda usar la clase Collection<T> genérica.Instead, we recommend that you use the generic Collection<T> class. Para obtener más información, consulte no se deben usar colecciones no genéricas en github.For more information, see Non-generic collections shouldn't be used on GitHub.

Una instancia de CollectionBase siempre es modificable.A CollectionBase instance is always modifiable. Vea ReadOnlyCollectionBase para obtener una versión de solo lectura de esta clase.See ReadOnlyCollectionBase for a read-only version of this class.

La capacidad de una CollectionBase es el número de elementos que puede contener el CollectionBase.The capacity of a CollectionBase is the number of elements the CollectionBase can hold. A medida que se agregan elementos a un CollectionBase, la capacidad aumenta automáticamente según sea necesario a través de la reasignación.As elements are added to a CollectionBase, the capacity is automatically increased as required through reallocation. La capacidad se puede reducir estableciendo la propiedad Capacity explícitamente.The capacity can be decreased by setting the Capacity property explicitly.

Notas a los implementadores

Esta clase base se proporciona para facilitar a los implementadores la creación de una colección personalizada fuertemente tipada.This base class is provided to make it easier for implementers to create a strongly typed custom collection. Se recomienda a los implementadores que amplíen esta clase base en lugar de crear las suyas propias.Implementers are encouraged to extend this base class instead of creating their own.

Constructores

CollectionBase()

Inicializa una nueva instancia de la clase CollectionBase con la funcionalidad inicial predeterminada.Initializes a new instance of the CollectionBase class with the default initial capacity.

CollectionBase(Int32)

Inicializa una nueva instancia de la clase CollectionBase con la capacidad especificada.Initializes a new instance of the CollectionBase class with the specified capacity.

Propiedades

Capacity

Obtiene o establece el número de elementos que puede contener CollectionBase.Gets or sets the number of elements that the CollectionBase can contain.

Count

Obtiene el número de elementos incluidos en la instancia de CollectionBase.Gets the number of elements contained in the CollectionBase instance. Esta propiedad no se puede invalidar.This property cannot be overridden.

InnerList

Obtiene una colección ArrayList que contiene la lista de elementos incluidos en la instancia de CollectionBase.Gets an ArrayList containing the list of elements in the CollectionBase instance.

List

Obtiene una colección IList que contiene la lista de elementos incluidos en la instancia de CollectionBase.Gets an IList containing the list of elements in the CollectionBase instance.

Métodos

Clear()

Elimina todos los objetos de la instancia de CollectionBase.Removes all objects from the CollectionBase instance. Este método no se puede invalidar.This method cannot be overridden.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
GetEnumerator()

Devuelve un enumerador que recorre en iteración la instancia de CollectionBase.Returns an enumerator that iterates through the CollectionBase instance.

GetHashCode()

Sirve como 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)
OnClear()

Realiza procesos personalizados adicionales al borrar el contenido de la instancia CollectionBase.Performs additional custom processes when clearing the contents of the CollectionBase instance.

OnClearComplete()

Realiza procesos personalizados adicionales después de borrar el contenido de la instancia de CollectionBase.Performs additional custom processes after clearing the contents of the CollectionBase instance.

OnInsert(Int32, Object)

Realiza procesos personalizados adicionales antes de insertar un nuevo elemento en la instancia de CollectionBase.Performs additional custom processes before inserting a new element into the CollectionBase instance.

OnInsertComplete(Int32, Object)

Realiza procesos personalizados adicionales después de insertar un nuevo elemento en la instancia de CollectionBase.Performs additional custom processes after inserting a new element into the CollectionBase instance.

OnRemove(Int32, Object)

Realiza procesos de personalización adicionales al quitar un elemento de la instancia de CollectionBase.Performs additional custom processes when removing an element from the CollectionBase instance.

OnRemoveComplete(Int32, Object)

Realiza procesos personalizados adicionales después de quitar un elemento de la instancia de CollectionBase.Performs additional custom processes after removing an element from the CollectionBase instance.

OnSet(Int32, Object, Object)

Realiza procesos personalizados adicionales antes de establecer un valor en la instancia de CollectionBase.Performs additional custom processes before setting a value in the CollectionBase instance.

OnSetComplete(Int32, Object, Object)

Realiza procesos personalizados adicionales después de establecer un valor en la instancia de CollectionBase.Performs additional custom processes after setting a value in the CollectionBase instance.

OnValidate(Object)

Realiza procesos de personalización adicionales al validar un valor.Performs additional custom processes when validating a value.

RemoveAt(Int32)

Quita el elemento que se encuentra en el índice especificado de la instancia de CollectionBase.Removes the element at the specified index of the CollectionBase instance. Este método no se puede reemplazar.This method is not overridable.

ToString()

Devuelve un valor de tipo string 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 la totalidad de CollectionBase en una matriz Array unidimensional compatible, comenzando en el índice especificado de la matriz de destino.Copies the entire CollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array.

ICollection.IsSynchronized

Obtiene un valor que indica si el acceso a la interfaz CollectionBase está sincronizado (es seguro para subprocesos).Gets a value indicating whether access to the CollectionBase is synchronized (thread safe).

ICollection.SyncRoot

Obtiene un objeto que se puede usar para sincronizar el acceso a CollectionBase.Gets an object that can be used to synchronize access to the CollectionBase.

IList.Add(Object)

Agrega un objeto al final de CollectionBase.Adds an object to the end of the CollectionBase.

IList.Contains(Object)

Determina si CollectionBase contiene un elemento específico.Determines whether the CollectionBase contains a specific element.

IList.IndexOf(Object)

Busca el objeto Object especificado y devuelve el índice de base cero de la primera aparición en toda la colección CollectionBase.Searches for the specified Object and returns the zero-based index of the first occurrence within the entire CollectionBase.

IList.Insert(Int32, Object)

Inserta un elemento en CollectionBase en el índice especificado.Inserts an element into the CollectionBase at the specified index.

IList.IsFixedSize

Obtiene un valor que indica si la interfaz CollectionBase tiene un tamaño fijo.Gets a value indicating whether the CollectionBase has a fixed size.

IList.IsReadOnly

Obtiene un valor que indica si CollectionBase es de solo lectura.Gets a value indicating whether the CollectionBase is read-only.

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 la primera aparición de un objeto específico de la interfaz CollectionBase.Removes the first occurrence of a specific object from the CollectionBase.

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.

Se aplica a

Seguridad para subprocesos

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para subprocesos.Public static (Shared in Visual Basic) members of this type are thread safe. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.Any instance members are not guaranteed to be thread safe.

Esta implementación no proporciona un contenedor sincronizado (seguro para subprocesos) para un CollectionBase, pero las clases derivadas pueden crear sus propias versiones sincronizadas de la CollectionBase mediante la propiedad SyncRoot.This implementation does not provide a synchronized (thread safe) wrapper for a CollectionBase, but derived classes can create their own synchronized versions of the CollectionBase using the SyncRoot property.

La enumeración a través de una colección no es intrínsecamente un procedimiento seguro para subprocesos.Enumerating through a collection is intrinsically not a thread safe procedure. Incluso cuando una colección está sincronizada, otros subprocesos todavía pueden modificarla, lo que hace que el enumerador produzca una excepción.Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. Con el fin de garantizar la seguridad para la ejecución de subprocesos durante la enumeración, se puede bloquear la colección durante toda la enumeración o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Consulte también: