Sdílet prostřednictvím


CollectionBase Třída

Definice

abstract Poskytuje základní třídu pro kolekci se silnými typy.

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
Dědičnost
CollectionBase
Odvozené
Atributy
Implementuje

Příklady

Následující příklad kódu implementuje CollectionBase třídu a používá tuto implementaci k vytvoření kolekce Int16 objektů.

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

Poznámky

Důležité

Nedoporučujeme používat CollectionBase třídu pro nový vývoj. Místo toho doporučujeme použít obecnou Collection<T> třídu. Další informace najdete v tématu Ne generické kolekce, které by se neměly používat na GitHubu.

Instance CollectionBase je vždy upravitelná. Podívejte ReadOnlyCollectionBase se na verzi této třídy určenou jen pro čtení.

Kapacita je CollectionBase počet prvků, které CollectionBase může obsahovat. S tím, jak jsou prvky přidány do CollectionBase, kapacita se automaticky zvýší podle potřeby prostřednictvím reallocation. Kapacitu lze snížit nastavením Capacity vlastnosti explicitně.

Poznámky pro implementátory

Tato základní třída je poskytována, aby bylo pro implementátory jednodušší vytvořit vlastní kolekci silného typu. Implementátory se doporučuje rozšířit tuto základní třídu namísto vytváření vlastních.

Konstruktory

Name Description
CollectionBase()

Inicializuje novou instanci CollectionBase třídy s výchozí počáteční kapacitou.

CollectionBase(Int32)

Inicializuje novou instanci CollectionBase třídy se zadanou kapacitou.

Vlastnosti

Name Description
Capacity

Získá nebo nastaví počet prvků, které CollectionBase může obsahovat.

Count

Získá počet prvků obsažených CollectionBase v instanci. Tuto vlastnost nelze přepsat.

InnerList

ArrayList Získá obsahující seznam prvků v CollectionBase instanci.

List

IList Získá obsahující seznam prvků v CollectionBase instanci.

Metody

Name Description
Clear()

Odebere všechny objekty z CollectionBase instance. Tuto metodu nelze přepsat.

Equals(Object)

Určuje, zda je zadaný objekt roven aktuálnímu objektu.

(Zděděno od Object)
GetEnumerator()

Vrátí enumerátor, který iteruje prostřednictvím CollectionBase instance.

GetHashCode()

Slouží jako výchozí funkce hash.

(Zděděno od Object)
GetType()

Získá Type aktuální instance.

(Zděděno od Object)
MemberwiseClone()

Vytvoří mělkou kopii aktuálního Object.

(Zděděno od Object)
OnClear()

Provádí další vlastní procesy při vymazání obsahu CollectionBase instance.

OnClearComplete()

Provádí další vlastní procesy po vymazání obsahu CollectionBase instance.

OnInsert(Int32, Object)

Provádí další vlastní procesy před vložením nového prvku do CollectionBase instance.

OnInsertComplete(Int32, Object)

Provede další vlastní procesy po vložení nového prvku do CollectionBase instance.

OnRemove(Int32, Object)

Provádí další vlastní procesy při odebírání elementu CollectionBase z instance.

OnRemoveComplete(Int32, Object)

Provádí další vlastní procesy po odebrání elementu CollectionBase z instance.

OnSet(Int32, Object, Object)

Před nastavením hodnoty v CollectionBase instanci provede další vlastní procesy.

OnSetComplete(Int32, Object, Object)

Provede další vlastní procesy po nastavení hodnoty v CollectionBase instanci.

OnValidate(Object)

Provádí další vlastní procesy při ověřování hodnoty.

RemoveAt(Int32)

Odebere prvek v zadaném indexu CollectionBase instance. Tato metoda není přepsatelná.

ToString()

Vrátí řetězec, který představuje aktuální objekt.

(Zděděno od Object)

Explicitní implementace rozhraní

Name Description
ICollection.CopyTo(Array, Int32)

Zkopíruje celý CollectionBase soubor do kompatibilního jednorozměrného Array, počínaje zadaným indexem cílového pole.

ICollection.IsSynchronized

Získá hodnotu označující, zda je přístup k CollectionBase této synchronizaci (bezpečné vlákno).

ICollection.SyncRoot

Získá objekt, který lze použít k synchronizaci přístupu k CollectionBase.

IList.Add(Object)

Přidá objekt na konec objektu CollectionBase.

IList.Contains(Object)

Určuje, zda obsahuje CollectionBase určitý prvek.

IList.IndexOf(Object)

Vyhledá zadaný Object index a vrátí index založený na nule prvního výskytu v celém CollectionBaserozsahu .

IList.Insert(Int32, Object)

Vloží prvek do zadaného indexu CollectionBase .

IList.IsFixedSize

Získá hodnotu určující, zda CollectionBase má pevnou velikost.

IList.IsReadOnly

Získá hodnotu určující, zda je jen pro CollectionBase čtení.

IList.Item[Int32]

Získá nebo nastaví prvek v zadaném indexu.

IList.Remove(Object)

Odebere první výskyt konkrétního objektu z objektu CollectionBase.

Metody rozšíření

Name Description
AsParallel(IEnumerable)

Umožňuje paralelizaci dotazu.

AsQueryable(IEnumerable)

Převede IEnumerable na IQueryable.

Cast<TResult>(IEnumerable)

Přetypuje prvky IEnumerable na zadaný typ.

OfType<TResult>(IEnumerable)

Filtruje prvky IEnumerable na základě zadaného typu.

Platí pro

Bezpečný přístup z více vláken

Veřejné statické členy tohoto typu (Shared v jazyce Visual Basic) jsou bezpečné pro přístup z více vláken. U žádného člena instance není zaručena bezpečnost pro přístup z více vláken.

Tato implementace neposkytuje synchronizovaný obálka (thread safe) pro , CollectionBaseale odvozené třídy mohou vytvořit své vlastní synchronizované verze CollectionBase pomocí SyncRoot vlastnosti.

Výčet prostřednictvím kolekce není vnitřně bezpečným postupem vlákna. I když je kolekce synchronizována, ostatní vlákna mohou stále upravovat kolekci, což způsobí, že enumerátor vyvolá výjimku. Chcete-li zaručit bezpečnost vláken během výčtu, můžete buď uzamknout kolekci během celého výčtu, nebo zachytit výjimky vyplývající z změn provedených jinými vlákny.

Viz také