CollectionBase Klass

Definition

Tillhandahåller basklassen abstract för en starkt typad samling.

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
Arv
CollectionBase
Härledda
Attribut
Implementeringar

Exempel

I följande kodexempel implementeras CollectionBase klassen och implementeringen används för att skapa en samling 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

Kommentarer

Important

Vi rekommenderar inte att du använder CollectionBase klassen för ny utveckling. I stället rekommenderar vi att du använder den allmänna Collection<T> klassen. Mer information finns i Non-generic samlingar bör inte användas på GitHub.

En CollectionBase instans kan alltid ändras. Se ReadOnlyCollectionBase för en skrivskyddad version av den här klassen.

Kapaciteten för en CollectionBase är antalet element som CollectionBase kan hållas. När element läggs till i en CollectionBaseökar kapaciteten automatiskt efter behov genom omallokering. Kapaciteten kan minskas genom att uttryckligen ange egenskapen Capacity .

Anteckningar till implementerare

Den här basklassen tillhandahålls för att göra det enklare för implementerare att skapa en starkt typanpassad samling. Implementerare uppmuntras att utöka den här basklassen i stället för att skapa sin egen.

Konstruktorer

Name Description
CollectionBase()

Initierar en ny instans av CollectionBase klassen med standardinitieringskapaciteten.

CollectionBase(Int32)

Initierar en ny instans av CollectionBase klassen med den angivna kapaciteten.

Egenskaper

Name Description
Capacity

Hämtar eller anger antalet element som CollectionBase kan innehålla.

Count

Hämtar antalet element som finns i instansen CollectionBase . Den här egenskapen kan inte åsidosättas.

InnerList

Hämtar en ArrayList lista med element i instansen CollectionBase .

List

Hämtar en IList lista med element i instansen CollectionBase .

Metoder

Name Description
Clear()

Tar bort alla objekt från instansen CollectionBase . Den här metoden kan inte åsidosättas.

Equals(Object)

Avgör om det angivna objektet är lika med det aktuella objektet.

(Ärvd från Object)
GetEnumerator()

Returnerar en uppräkning som itererar genom instansen CollectionBase .

GetHashCode()

Fungerar som standard-hash-funktion.

(Ärvd från Object)
GetType()

Hämtar den aktuella instansen Type .

(Ärvd från Object)
MemberwiseClone()

Skapar en ytlig kopia av den aktuella Object.

(Ärvd från Object)
OnClear()

Utför ytterligare anpassade processer när du rensar innehållet i instansen CollectionBase .

OnClearComplete()

Utför ytterligare anpassade processer när innehållet i instansen har rensats CollectionBase .

OnInsert(Int32, Object)

Utför ytterligare anpassade processer innan du infogar ett nytt element i instansen CollectionBase .

OnInsertComplete(Int32, Object)

Utför ytterligare anpassade processer när du har infogat ett nytt element i instansen CollectionBase .

OnRemove(Int32, Object)

Utför ytterligare anpassade processer när du tar bort ett element från instansen CollectionBase .

OnRemoveComplete(Int32, Object)

Utför ytterligare anpassade processer när du har tagit bort ett element från instansen CollectionBase .

OnSet(Int32, Object, Object)

Utför ytterligare anpassade processer innan du anger ett värde i instansen CollectionBase .

OnSetComplete(Int32, Object, Object)

Utför ytterligare anpassade processer när du har angett ett värde i instansen CollectionBase .

OnValidate(Object)

Utför ytterligare anpassade processer när du verifierar ett värde.

RemoveAt(Int32)

Tar bort elementet vid det angivna indexet för instansen CollectionBase . Den här metoden kan inte åsidosättas.

ToString()

Returnerar en sträng som representerar det aktuella objektet.

(Ärvd från Object)

Explicita gränssnittsimplementeringar

Name Description
ICollection.CopyTo(Array, Int32)

Kopierar hela CollectionBase till en kompatibel endimensionell Array, med början vid det angivna indexet för målmatrisen.

ICollection.IsSynchronized

Hämtar ett värde som anger om åtkomsten CollectionBase till är synkroniserad (trådsäker).

ICollection.SyncRoot

Hämtar ett objekt som kan användas för att synkronisera åtkomsten CollectionBasetill .

IList.Add(Object)

Lägger till ett objekt i slutet av CollectionBase.

IList.Contains(Object)

Avgör om innehåller CollectionBase ett specifikt element.

IList.IndexOf(Object)

Söker efter den angivna Object och returnerar det nollbaserade indexet för den första förekomsten i hela CollectionBase.

IList.Insert(Int32, Object)

Infogar ett element i CollectionBase det angivna indexet.

IList.IsFixedSize

Hämtar ett värde som anger om har CollectionBase en fast storlek.

IList.IsReadOnly

Hämtar ett värde som anger om är CollectionBase skrivskyddat.

IList.Item[Int32]

Hämtar eller anger elementet vid det angivna indexet.

IList.Remove(Object)

Tar bort den första förekomsten av ett specifikt objekt från CollectionBase.

Tilläggsmetoder

Name Description
AsParallel(IEnumerable)

Möjliggör parallellisering av en fråga.

AsQueryable(IEnumerable)

Konverterar en IEnumerable till en IQueryable.

Cast<TResult>(IEnumerable)

Omvandlar elementen i en IEnumerable till den angivna typen.

OfType<TResult>(IEnumerable)

Filtrerar elementen i en IEnumerable baserat på en angiven typ.

Gäller för

Trådsäkerhet

Offentliga statiska (Shared i Visual Basic) medlemmar av den här typen är trådsäkra. Vilka som helst instansmedlemmar garanteras inte att vara trådsäkra.

Den här implementeringen tillhandahåller ingen synkroniserad (trådsäker) omslutning för en CollectionBase, men härledda klasser kan skapa sina egna synkroniserade versioner av CollectionBase egenskapen SyncRoot .

Att räkna upp genom en samling är i sig inte en trådsäker procedur. Även när en samling synkroniseras kan andra trådar fortfarande ändra samlingen, vilket gör att uppräknaren genererar ett undantag. För att garantera trådsäkerheten under uppräkningen kan du antingen låsa samlingen under hela uppräkningen eller fånga undantagen från ändringar som gjorts av andra trådar.

Se även