CollectionBase 類別

定義

為強類型集合提供 abstract 基底類別。Provides the abstract base class for a strongly typed collection.

public ref class CollectionBase abstract : System::Collections::IList
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class CollectionBase : System.Collections.IList
type CollectionBase = class
    interface IList
    interface ICollection
    interface IEnumerable
Public MustInherit Class CollectionBase
Implements IList
繼承
CollectionBase
衍生
屬性
實作

範例

下列程式碼範例會實作為 CollectionBase 類別,並使用該執行來建立 Int16 物件的集合。The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects.

#using <System.dll>

using namespace System;
using namespace System::Collections;

public ref class Int16Collection: public CollectionBase
{
public:

   property Int16 Item [int]
   {
      Int16 get( int index )
      {
         return ( (Int16)(List[ index ]));
      }

      void set( int index, Int16 value )
      {
         List[ index ] = value;
      }
   }
   int Add( Int16 value )
   {
      return (List->Add( value ));
   }

   int IndexOf( Int16 value )
   {
      return (List->IndexOf( value ));
   }

   void Insert( int index, Int16 value )
   {
      List->Insert( index, value );
   }

   void Remove( Int16 value )
   {
      List->Remove( value );
   }

   bool Contains( Int16 value )
   {
      // If value is not of type Int16, this will return false.
      return (List->Contains( value ));
   }

protected:
   virtual void OnInsert( int /*index*/, Object^ /*value*/ ) override
   {
      // Insert additional code to be run only when inserting values.
   }

   virtual void OnRemove( int /*index*/, Object^ /*value*/ ) override
   {
      // Insert additional code to be run only when removing values.
   }

   virtual void OnSet( int /*index*/, Object^ /*oldValue*/, Object^ /*newValue*/ ) override
   {
      // Insert additional code to be run only when setting values.
   }

   virtual void OnValidate( Object^ value ) override
   {
      if ( value->GetType() != Type::GetType( "System.Int16" ) )
            throw gcnew ArgumentException( "value must be of type Int16.","value" );
   }

};

void PrintIndexAndValues( Int16Collection^ myCol );
void PrintValues2( Int16Collection^ myCol );
int main()
{
   // Create and initialize a new CollectionBase.
   Int16Collection^ myI16 = gcnew 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 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->Item[ 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.
void PrintIndexAndValues( Int16Collection^ myCol )
{
   for ( int i = 0; i < myCol->Count; i++ )
      Console::WriteLine( "   [{0}]:   {1}", i, myCol->Item[ i ] );
   Console::WriteLine();
}

// Uses the enumerator. 
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 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

*/
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

備註

重要

我們不建議您使用 CollectionBase 類別來進行新的開發。We don't recommend that you use the CollectionBase class for new development. 相反地,我們建議您使用泛型 Collection<T> 類別。Instead, we recommend that you use the generic Collection<T> class. 如需詳細資訊,請參閱不應在 GitHub 上使用非泛型集合For more information, see Non-generic collections shouldn't be used on GitHub.

CollectionBase 實例永遠都是可修改的。A CollectionBase instance is always modifiable. 請參閱此類別之唯讀版本的 ReadOnlyCollectionBaseSee ReadOnlyCollectionBase for a read-only version of this class.

CollectionBase 的容量是 CollectionBase 可以保存的元素數目。The capacity of a CollectionBase is the number of elements the CollectionBase can hold. 當專案新增至 CollectionBase時,會視需要透過重新配置來自動增加容量。As elements are added to a CollectionBase, the capacity is automatically increased as required through reallocation. 您可以明確地設定 Capacity 屬性來降低容量。The capacity can be decreased by setting the Capacity property explicitly.

給實施者的注意事項

提供這個基類的目的,是為了讓實施者能夠更輕鬆地建立強型別自訂集合。This base class is provided to make it easier for implementers to create a strongly typed custom collection. 建議實施者擴充此基類,而不是建立自己的類別。Implementers are encouraged to extend this base class instead of creating their own.

建構函式

CollectionBase()

初始化 CollectionBase 類別的新執行個體,並將其初始容量設定為預設值。Initializes a new instance of the CollectionBase class with the default initial capacity.

CollectionBase(Int32)

初始化 CollectionBase 類別的新執行個體,並將其容量設定為指定值。Initializes a new instance of the CollectionBase class with the specified capacity.

屬性

Capacity

取得或設定 CollectionBase 可包含的項目數目。Gets or sets the number of elements that the CollectionBase can contain.

Count

取得包含在 CollectionBase 執行個體中的項目數目。Gets the number of elements contained in the CollectionBase instance. 這個屬性無法覆寫。This property cannot be overridden.

InnerList

取得包含 ArrayList 執行個體中之元素清單的 CollectionBaseGets an ArrayList containing the list of elements in the CollectionBase instance.

List

取得包含 IList 執行個體中之元素清單的 CollectionBaseGets an IList containing the list of elements in the CollectionBase instance.

方法

Clear()

CollectionBase 執行個體移除所有的物件。Removes all objects from the CollectionBase instance. 無法覆寫這個方法。This method cannot be overridden.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetEnumerator()

傳回可逐一查看 CollectionBase 執行個體的列舉值。Returns an enumerator that iterates through the CollectionBase instance.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
OnClear()

在清除 CollectionBase 執行個體的內容之後,執行額外的自訂處理序。Performs additional custom processes when clearing the contents of the CollectionBase instance.

OnClearComplete()

在清除 CollectionBase 執行個體的內容後,執行額外的自訂處理序。Performs additional custom processes after clearing the contents of the CollectionBase instance.

OnInsert(Int32, Object)

在將新的元素插入至 CollectionBase 執行個體前,執行額外的自訂處理序。Performs additional custom processes before inserting a new element into the CollectionBase instance.

OnInsertComplete(Int32, Object)

在將新的元素插入至 CollectionBase 執行個體後,執行額外的自訂處理序。Performs additional custom processes after inserting a new element into the CollectionBase instance.

OnRemove(Int32, Object)

當從 CollectionBase 執行個體移除元素時,執行額外的自訂處理序。Performs additional custom processes when removing an element from the CollectionBase instance.

OnRemoveComplete(Int32, Object)

在從 CollectionBase 執行個體移除元素後,執行額外的自訂處理序。Performs additional custom processes after removing an element from the CollectionBase instance.

OnSet(Int32, Object, Object)

CollectionBase 執行個體中設定數值前,執行額外的自訂處理序。Performs additional custom processes before setting a value in the CollectionBase instance.

OnSetComplete(Int32, Object, Object)

CollectionBase 執行個體中設定數值後,執行額外的自訂處理序。Performs additional custom processes after setting a value in the CollectionBase instance.

OnValidate(Object)

當驗證數值時,執行額外的自訂處理序。Performs additional custom processes when validating a value.

RemoveAt(Int32)

移除 CollectionBase 執行個體之指定索引的元素。Removes the element at the specified index of the CollectionBase instance. 這個方法不可覆寫。This method is not overridable.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

ICollection.CopyTo(Array, Int32)

從目標陣列的指定索引開始,將整個 CollectionBase 複製到相容的一維 ArrayCopies the entire CollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array.

ICollection.IsSynchronized

取得值,這個值表示對 CollectionBase 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the CollectionBase is synchronized (thread safe).

ICollection.SyncRoot

取得可用以同步存取 CollectionBase 的物件。Gets an object that can be used to synchronize access to the CollectionBase.

IList.Add(Object)

將物件加入至 CollectionBase 的末端。Adds an object to the end of the CollectionBase.

IList.Contains(Object)

判斷 CollectionBase 是否含有特定元素。Determines whether the CollectionBase contains a specific element.

IList.IndexOf(Object)

搜尋指定的 Object,並傳回在整個 CollectionBase 中第一個符合項目之以零為起始的索引。Searches for the specified Object and returns the zero-based index of the first occurrence within the entire CollectionBase.

IList.Insert(Int32, Object)

將項目插入至 CollectionBase 中指定的索引位置。Inserts an element into the CollectionBase at the specified index.

IList.IsFixedSize

取得值,指出 CollectionBase 是否有固定的大小。Gets a value indicating whether the CollectionBase has a fixed size.

IList.IsReadOnly

取得值,指出 CollectionBase 是否唯讀。Gets a value indicating whether the CollectionBase is read-only.

IList.Item[Int32]

在指定的索引位置上取得或設定項目。Gets or sets the element at the specified index.

IList.Remove(Object)

CollectionBase 移除特定物件之第一個符合的元素。Removes the first occurrence of a specific object from the CollectionBase.

擴充方法

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

啟用查詢的平行化作業。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryableConverts an IEnumerable to an IQueryable.

適用於

執行緒安全性

此類型的公用靜態(Shared 在 Visual Basic 中)成員是安全線程。Public static (Shared in Visual Basic) members of this type are thread safe. 不保證任何執行個體成員是安全執行緒。Any instance members are not guaranteed to be thread safe.

這個執行不會提供 CollectionBase的同步處理(安全線程)包裝函式,但衍生的類別可以使用 SyncRoot 屬性來建立自己的 CollectionBase 同步處理版本。This implementation does not provide a synchronized (thread safe) wrapper for a CollectionBase, but derived classes can create their own synchronized versions of the CollectionBase using the SyncRoot property.

透過集合進行列舉,本質上並不是安全線程的程式。Enumerating through a collection is intrinsically not a thread safe procedure. 即使集合經過同步化,其他的執行緒仍可修改該集合,使列舉值擲回例外狀況。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要保證列舉過程的執行緒安全,您可以在整個列舉過程中鎖定集合,或攔截由其他執行緒的變更所造成的例外狀況。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

另請參閱