Condividi tramite


CollectionBase Classe

Definizione

Fornisce la abstract classe base per una raccolta fortemente tipizzata.

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
Ereditarietà
CollectionBase
Derivato
Attributi
Implementazioni

Esempio

Nell'esempio di codice seguente viene implementata la classe e viene utilizzata tale CollectionBase implementazione per creare una raccolta di Int16 oggetti .

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

Commenti

Importante

Non è consigliabile usare la CollectionBase classe per il nuovo sviluppo. È invece consigliabile usare la classe generica Collection<T> . Per altre informazioni, vedere Raccolte non generiche che non devono essere usate in GitHub.

Un'istanza CollectionBase è sempre modificabile. Vedere ReadOnlyCollectionBase per una versione di sola lettura di questa classe.

La capacità di un CollectionBase oggetto è il numero di elementi che può CollectionBase contenere. Man mano che gli elementi vengono aggiunti a un CollectionBaseoggetto , la capacità viene aumentata automaticamente in base alle esigenze tramite la riallocazione. La capacità può essere ridotta impostando la Capacity proprietà in modo esplicito.

Note per gli implementatori

Questa classe di base viene fornita per semplificare la creazione di una raccolta personalizzata fortemente tipizzata da parte degli implementatori. Gli implementatori sono invitati a estendere questa classe di base anziché crearne una propria.

Costruttori

Nome Descrizione
CollectionBase()

Inizializza una nuova istanza della CollectionBase classe con la capacità iniziale predefinita.

CollectionBase(Int32)

Inizializza una nuova istanza della CollectionBase classe con la capacità specificata.

Proprietà

Nome Descrizione
Capacity

Ottiene o imposta il numero di elementi che l'oggetto CollectionBase può contenere.

Count

Ottiene il numero di elementi contenuti nell'istanza CollectionBase di . Impossibile eseguire l'override di questa proprietà.

InnerList

Ottiene un oggetto ArrayList contenente l'elenco di elementi nell'istanza CollectionBase di .

List

Ottiene un oggetto IList contenente l'elenco di elementi nell'istanza CollectionBase di .

Metodi

Nome Descrizione
Clear()

Rimuove tutti gli oggetti dall'istanza CollectionBase di . Non è possibile eseguire l'override di questo metodo.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetEnumerator()

Restituisce un enumeratore che scorre l'istanza CollectionBase di .

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
OnClear()

Esegue processi personalizzati aggiuntivi quando si cancella il contenuto dell'istanza CollectionBase .

OnClearComplete()

Esegue processi personalizzati aggiuntivi dopo la cancellazione del contenuto dell'istanza CollectionBase .

OnInsert(Int32, Object)

Esegue processi personalizzati aggiuntivi prima di inserire un nuovo elemento nell'istanza CollectionBase di .

OnInsertComplete(Int32, Object)

Esegue processi personalizzati aggiuntivi dopo l'inserimento di un nuovo elemento nell'istanza CollectionBase di .

OnRemove(Int32, Object)

Esegue processi personalizzati aggiuntivi durante la rimozione di un elemento dall'istanza CollectionBase di .

OnRemoveComplete(Int32, Object)

Esegue processi personalizzati aggiuntivi dopo la rimozione di un elemento dall'istanza CollectionBase di .

OnSet(Int32, Object, Object)

Esegue processi personalizzati aggiuntivi prima di impostare un valore nell'istanza CollectionBase di .

OnSetComplete(Int32, Object, Object)

Esegue processi personalizzati aggiuntivi dopo aver impostato un valore nell'istanza CollectionBase di .

OnValidate(Object)

Esegue processi personalizzati aggiuntivi durante la convalida di un valore.

RemoveAt(Int32)

Rimuove l'elemento in corrispondenza dell'indice specificato dell'istanza CollectionBase . Questo metodo non è sostituibile.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

Nome Descrizione
ICollection.CopyTo(Array, Int32)

Copia l'intero CollectionBase oggetto in un oggetto unidimensionale Arraycompatibile, a partire dall'indice specificato della matrice di destinazione.

ICollection.IsSynchronized

Ottiene un valore che indica se l'accesso CollectionBase a è sincronizzato (thread-safe).

ICollection.SyncRoot

Ottiene un oggetto che può essere utilizzato per sincronizzare l'accesso all'oggetto CollectionBase.

IList.Add(Object)

Aggiunge un oggetto alla fine dell'oggetto CollectionBase.

IList.Contains(Object)

Determina se contiene CollectionBase un elemento specifico.

IList.IndexOf(Object)

Cerca l'oggetto specificato Object e restituisce l'indice in base zero della prima occorrenza all'interno dell'intero CollectionBaseoggetto .

IList.Insert(Int32, Object)

Inserisce un elemento nell'oggetto CollectionBase in corrispondenza dell'indice specificato.

IList.IsFixedSize

Ottiene un valore che indica se ha CollectionBase una dimensione fissa.

IList.IsReadOnly

Ottiene un valore che indica se l'oggetto CollectionBase è di sola lettura.

IList.Item[Int32]

Ottiene o imposta l'elemento in corrispondenza dell'indice specificato.

IList.Remove(Object)

Rimuove la prima occorrenza di un oggetto specifico da CollectionBase.

Metodi di estensione

Nome Descrizione
AsParallel(IEnumerable)

Abilita la parallelizzazione di una query.

AsQueryable(IEnumerable)

Converte un IEnumerable in un IQueryable.

Cast<TResult>(IEnumerable)

Esegue il cast degli elementi di un IEnumerable al tipo specificato.

OfType<TResult>(IEnumerable)

Filtra gli elementi di un IEnumerable in base a un tipo specificato.

Si applica a

Thread safety

I membri statici pubblici (Shared in Visual Basic) di questo tipo sono thread-safe. Non è garantito che tutti i membri dell'istanza siano thread-safe.

Questa implementazione non fornisce un wrapper sincronizzato (thread-safe) per un oggetto CollectionBase, ma le classi derivate possono creare versioni sincronizzate dell'oggetto CollectionBase usando la SyncRoot proprietà .

L'enumerazione tramite una raccolta non è intrinsecamente una procedura thread-safe. Anche quando una raccolta viene sincronizzata, altri thread possono comunque modificare la raccolta, causando la generazione di un'eccezione da parte dell'enumeratore. Per garantire la thread safety durante l'enumerazione, è possibile bloccare la raccolta durante l'intera enumerazione o intercettare le eccezioni risultanti dalle modifiche apportate da altri thread.

Vedi anche