CollectionBase Klasa

Definicja

Udostępnia klasę abstract bazową dla silnie typizowanej kolekcji.

C#
public abstract class CollectionBase : System.Collections.IList
C#
[System.Serializable]
public abstract class CollectionBase : System.Collections.IList
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CollectionBase : System.Collections.IList
Dziedziczenie
CollectionBase
Pochodne
Atrybuty
Implementuje

Przykłady

Poniższy przykład kodu implementuje klasę CollectionBase i używa tej implementacji do utworzenia kolekcji Int16 obiektów.

C#
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

*/

Uwagi

Ważne

Nie zalecamy używania CollectionBase klasy do nowego programowania. Zamiast tego zalecamy użycie klasy ogólnej Collection<T> . Aby uzyskać więcej informacji, zobacz Kolekcje inne niż ogólne nie powinny być używane w usłudze GitHub.

Wystąpienie CollectionBase jest zawsze modyfikowalne. Zobacz, aby zapoznać się ReadOnlyCollectionBase z wersją tej klasy tylko do odczytu.

Pojemność elementu CollectionBase to liczba elementów, które CollectionBase może pomieścić. Ponieważ elementy są dodawane do elementu CollectionBase, pojemność jest automatycznie zwiększana zgodnie z wymaganiami za pośrednictwem reallocation. Pojemność można zmniejszyć, ustawiając Capacity jawnie właściwość.

Uwagi dotyczące implementowania

Ta klasa bazowa jest udostępniana, aby ułatwić implementatorom tworzenie silnie typizowanej kolekcji niestandardowej. Implementacje są zachęcane do rozszerzania tej klasy bazowej zamiast tworzenia własnych.

Konstruktory

CollectionBase()

Inicjuje CollectionBase nowe wystąpienie klasy z domyślną pojemnością początkową.

CollectionBase(Int32)

Inicjuje nowe wystąpienie klasy CollectionBase z określoną wydajnością.

Właściwości

Capacity

Pobiera lub ustawia liczbę elementów, które CollectionBase mogą zawierać.

Count

Pobiera liczbę elementów zawartych w wystąpieniu CollectionBase . Nie można zastąpić tej właściwości.

InnerList

Pobiera element ArrayList zawierający listę elementów w wystąpieniu CollectionBase .

List

Pobiera element IList zawierający listę elementów w wystąpieniu CollectionBase .

Metody

Clear()

Usuwa wszystkie obiekty z CollectionBase wystąpienia. Nie można zastąpić tej metody.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetEnumerator()

Zwraca moduł wyliczający, który iteruje za pośrednictwem CollectionBase wystąpienia.

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
OnClear()

Wykonuje dodatkowe procesy niestandardowe podczas czyszczenia zawartości CollectionBase wystąpienia.

OnClearComplete()

Wykonuje dodatkowe procesy niestandardowe po wyczyszczeniu zawartości CollectionBase wystąpienia.

OnInsert(Int32, Object)

Wykonuje dodatkowe procesy niestandardowe przed wstawieniem nowego elementu do CollectionBase wystąpienia.

OnInsertComplete(Int32, Object)

Wykonuje dodatkowe procesy niestandardowe po wstawieniu nowego elementu do CollectionBase wystąpienia.

OnRemove(Int32, Object)

Wykonuje dodatkowe procesy niestandardowe podczas usuwania elementu z CollectionBase wystąpienia.

OnRemoveComplete(Int32, Object)

Wykonuje dodatkowe procesy niestandardowe po usunięciu CollectionBase elementu z wystąpienia.

OnSet(Int32, Object, Object)

Wykonuje dodatkowe procesy niestandardowe przed ustawieniem wartości w wystąpieniu CollectionBase .

OnSetComplete(Int32, Object, Object)

Wykonuje dodatkowe procesy niestandardowe po ustawieniu wartości w wystąpieniu CollectionBase .

OnValidate(Object)

Wykonuje dodatkowe procesy niestandardowe podczas sprawdzania poprawności wartości.

RemoveAt(Int32)

Usuwa element w określonym indeksie CollectionBase wystąpienia. Ta metoda nie jest zastępowana.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

ICollection.CopyTo(Array, Int32)

Kopiuje całą CollectionBase do zgodnej jednowymiarowej Arraytablicy, zaczynając od określonego indeksu tablicy docelowej.

ICollection.IsSynchronized

Pobiera wartość wskazującą, czy dostęp do elementu CollectionBase jest synchronizowany (bezpieczny wątek).

ICollection.SyncRoot

Pobiera obiekt, który może służyć do synchronizowania dostępu do obiektu CollectionBase.

IList.Add(Object)

Dodaje obiekt na końcu obiektu CollectionBase.

IList.Contains(Object)

Określa, czy element CollectionBase zawiera określony element.

IList.IndexOf(Object)

Wyszukuje określony Object element i zwraca indeks oparty na zerowym pierwszym wystąpieniu w całym CollectionBaseobiekcie .

IList.Insert(Int32, Object)

Wstawia element do CollectionBase określonego indeksu.

IList.IsFixedSize

Pobiera wartość wskazującą, czy rozmiar CollectionBase ma stały rozmiar.

IList.IsReadOnly

Pobiera wartość wskazującą, czy kolekcja CollectionBase jest przeznaczona tylko do odczytu.

IList.Item[Int32]

Pobiera lub ustawia element pod określonym indeksem.

IList.Remove(Object)

Usuwa pierwsze wystąpienie określonego obiektu z obiektu CollectionBase.

Metody rozszerzania

Cast<TResult>(IEnumerable)

Rzutuje elementy elementu IEnumerable do określonego typu.

OfType<TResult>(IEnumerable)

Filtruje elementy elementu IEnumerable na podstawie określonego typu.

AsParallel(IEnumerable)

Umożliwia równoległość zapytania.

AsQueryable(IEnumerable)

Konwertuje element IEnumerable na .IQueryable

Dotyczy

Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

Bezpieczeństwo wątkowe

Publiczne statyczne (Shared w Visual Basic) elementy członkowskie tego typu są bezpieczne wątkami. Wystąpienia elementów członkowskich nie dają gwarancji bezpieczeństwa wątków.

Ta implementacja nie zapewnia zsynchronizowanej otoki (bezpiecznej wątku) dla klasy pochodnej CollectionBase, ale klasy pochodne mogą tworzyć własne zsynchronizowane wersje CollectionBase właściwości SyncRoot .

Wyliczanie przez kolekcję nie jest wewnętrznie bezpieczną procedurą wątku. Nawet gdy kolekcja jest synchronizowana, inne wątki nadal mogą ją modyfikować. Powoduje to zgłaszanie wyjątku przez moduł wyliczający. Aby zagwarantować bezpieczeństwo wątków podczas wyliczania, można zablokować kolekcję podczas całego procesu wyliczania albo rejestrować wyjątki wynikłe ze zmian wprowadzanych przez inne wątków.

Zobacz też