CollectionBase Class

정의

강력한 형식의 컬렉션에 대한 abstract 기본 클래스를 제공합니다. Provides the abstract base class for a strongly typed collection.

[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CollectionBase : System.Collections.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
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 'Insert


   Public Sub Remove(value As Int16)
      List.Remove(value)
   End Sub 'Remove


   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 'OnInsert


   Protected Overrides Sub OnRemove(index As Integer, value As Object)
      ' Insert additional code to be run only when removing values.
   End Sub 'OnRemove


   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 'OnSet


   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 'OnValidate 

End Class 'Int16Collection


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 'Main


    ' 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 'PrintIndexAndValues


    ' 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 'PrintValues1


    ' 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 'PrintValues2

End Class 'SamplesCollectionBase


'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 인스턴스는 항상 수정할 수 있습니다.A CollectionBase instance is always modifiable. 참조 ReadOnlyCollectionBase 이 클래스의 읽기 전용 버전입니다.See 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 인스턴스의 요소 목록을 포함하는 CollectionBase를 가져옵니다. Gets an ArrayList containing the list of elements in the CollectionBase instance.

List

IList 인스턴스의 요소 목록을 포함하는 CollectionBase를 가져옵니다. Gets 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.

(Inherited from Object)
GetEnumerator()

CollectionBase 인스턴스를 반복하는 열거자를 반환합니다. Returns an enumerator that iterates through the CollectionBase instance.

GetHashCode()

기본 해시 함수로 작동합니다. Serves as the default hash function.

(Inherited from Object)
GetType()

현재 인스턴스의 Type을 가져옵니다. Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다. Creates a shallow copy of the current Object.

(Inherited from 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.

(Inherited from Object)

명시적 인터페이스 구현

ICollection.CopyTo(Array, Int32)

대상 배열의 지정된 인덱스에서 시작하여 전체 CollectionBase을 호환되는 1차원 Array에 복사합니다. Copies 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 내에서 처음 나오는 0부터 시작하는 인덱스를 반환합니다. 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.

적용 대상

스레드 보안

공용 정적 (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, 파생된 클래스의 자체 동기화 된 버전을 만들 수 있지만 CollectionBase 사용 하 여를 SyncRoot 속성. 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. 컬렉션이 동기화되어 있을 때 다른 스레드에서 해당 컬렉션을 수정할 수 있으므로 이렇게 되면 열거자에서 예외가 throw됩니다. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 열거하는 동안 스레드로부터 안전을 보장하려면 전체 열거를 수행하는 동안 컬렉션을 잠그거나 다른 스레드에서 변경된 내용으로 인해 발생한 예외를 catch하면 됩니다. 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.

추가 정보