Compartir a través de


CollectionBase Clase

Definición

Proporciona la abstract clase base para una colección fuertemente tipada.

public ref class CollectionBase abstract : System::Collections::IList
public abstract class CollectionBase : System.Collections.IList
[System.Serializable]
public abstract class CollectionBase : System.Collections.IList
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CollectionBase : System.Collections.IList
type CollectionBase = class
    interface ICollection
    interface IEnumerable
    interface IList
[<System.Serializable>]
type CollectionBase = class
    interface IList
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
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 CollectionBase clase y se usa esa implementación para crear una colección de Int16 objetos .

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 CollectionBase clase para el nuevo desarrollo. En su lugar, se recomienda usar la clase genérica Collection<T> . Para obtener más información, consulte Colecciones no genéricas no deben usarse en GitHub.

Una CollectionBase instancia siempre se puede modificar. Consulte ReadOnlyCollectionBase para obtener una versión de solo lectura de esta clase.

La capacidad de es CollectionBase el número de elementos que CollectionBase puede contener. A medida que se agregan elementos a , CollectionBasela capacidad aumenta automáticamente según sea necesario mediante la reasignación. La capacidad se puede reducir estableciendo la Capacity propiedad explícitamente.

Notas a los implementadores

Esta clase base se proporciona para facilitar a los implementadores crear una colección personalizada fuertemente tipada. Se recomienda a los implementadores ampliar esta clase base en lugar de crear sus propias.

Constructores

Nombre Description
CollectionBase()

Inicializa una nueva instancia de la CollectionBase clase con la capacidad inicial predeterminada.

CollectionBase(Int32)

Inicializa una nueva instancia de la CollectionBase clase con la capacidad especificada.

Propiedades

Nombre Description
Capacity

Obtiene o establece el número de elementos que CollectionBase puede contener.

Count

Obtiene el número de elementos contenidos en la CollectionBase instancia. Esta propiedad no se puede invalidar.

InnerList

Obtiene un ArrayList objeto que contiene la lista de elementos de la CollectionBase instancia de .

List

Obtiene un IList objeto que contiene la lista de elementos de la CollectionBase instancia de .

Métodos

Nombre Description
Clear()

Quita todos los objetos de la CollectionBase instancia. Este método no se puede invalidar.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetEnumerator()

Devuelve un enumerador que recorre en iteración la CollectionBase instancia de .

GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
OnClear()

Realiza procesos personalizados adicionales al borrar el contenido de la CollectionBase instancia.

OnClearComplete()

Realiza procesos personalizados adicionales después de borrar el contenido de la CollectionBase instancia.

OnInsert(Int32, Object)

Realiza procesos personalizados adicionales antes de insertar un nuevo elemento en la CollectionBase instancia.

OnInsertComplete(Int32, Object)

Realiza procesos personalizados adicionales después de insertar un nuevo elemento en la CollectionBase instancia.

OnRemove(Int32, Object)

Realiza procesos personalizados adicionales al quitar un elemento de la CollectionBase instancia.

OnRemoveComplete(Int32, Object)

Realiza procesos personalizados adicionales después de quitar un elemento de la CollectionBase instancia.

OnSet(Int32, Object, Object)

Realiza procesos personalizados adicionales antes de establecer un valor en la CollectionBase instancia de .

OnSetComplete(Int32, Object, Object)

Realiza procesos personalizados adicionales después de establecer un valor en la CollectionBase instancia de .

OnValidate(Object)

Realiza procesos personalizados adicionales al validar un valor.

RemoveAt(Int32)

Quita el elemento en el índice especificado de la CollectionBase instancia. Este método no se puede invalidar.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

Nombre Description
ICollection.CopyTo(Array, Int32)

Copia todo en CollectionBase una unidimensional Arraycompatible, empezando por el índice especificado de la matriz de destino.

ICollection.IsSynchronized

Obtiene un valor que indica si el acceso a CollectionBase está sincronizado (seguro para subprocesos).

ICollection.SyncRoot

Obtiene un objeto que se puede usar para sincronizar el acceso a .CollectionBase

IList.Add(Object)

Agrega un objeto al final de .CollectionBase

IList.Contains(Object)

Determina si contiene CollectionBase un elemento específico.

IList.IndexOf(Object)

Busca el especificado Object y devuelve el índice de base cero de la primera aparición dentro de todo CollectionBase.

IList.Insert(Int32, Object)

Inserta un elemento en en el CollectionBase índice especificado.

IList.IsFixedSize

Obtiene un valor que indica si CollectionBase tiene un tamaño fijo.

IList.IsReadOnly

Obtiene un valor que indica si es CollectionBase de solo lectura.

IList.Item[Int32]

Obtiene o establece el elemento en el índice especificado.

IList.Remove(Object)

Quita la primera aparición de un objeto específico de .CollectionBase

Métodos de extensión

Nombre Description
AsParallel(IEnumerable)

Habilita la paralelización de una consulta.

AsQueryable(IEnumerable)

Convierte un IEnumerable en un IQueryable.

Cast<TResult>(IEnumerable)

Convierte los elementos de un IEnumerable al tipo especificado.

OfType<TResult>(IEnumerable)

Filtra los elementos de un IEnumerable en función de un tipo especificado.

Se aplica a

Seguridad para subprocesos

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para subprocesos. No se garantiza que los miembros de instancia sean seguros para el acceso concurrente.

Esta implementación no proporciona un contenedor sincronizado (seguro para subprocesos) para una CollectionBaseclase , pero las clases derivadas pueden crear sus propias versiones sincronizadas de CollectionBase mediante la SyncRoot propiedad .

La enumeración a través de una colección no es intrínsecamente un procedimiento seguro para subprocesos. Incluso cuando se sincroniza una colección, otros subprocesos todavía pueden modificar la colección, lo que hace que el enumerador inicie una excepción. Para garantizar la seguridad de los subprocesos durante la enumeración, puede bloquear la colección durante toda la enumeración o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.

Consulte también