CollectionBase 클래스

정의

강력한 형식의 컬렉션에 대한 abstract 기본 클래스를 제공합니다.

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
상속
CollectionBase
파생
특성
구현

예제

다음 코드 예제에서는 클래스를 CollectionBase 구현 하 고 개체의 Int16 컬렉션을 만드는 해당 구현을 사용 합니다.

#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 사용하지 않는 것이 좋습니다. 대신 제네릭 Collection<T> 클래스를 사용하는 것이 좋습니다. 자세한 내용은 GitHub 사용할 수 없는 제네릭이 아닌 컬렉션을 참조하세요.

CollectionBase 인스턴스는 항상 수정할 수 있습니다. 이 클래스의 읽기 전용 버전을 참조 ReadOnlyCollectionBase 하세요.

용량은 CollectionBase 보유할 수 있는 CollectionBase 요소의 수입니다. 요소가 추가 CollectionBase되면 재할당을 통해 필요에 따라 용량이 자동으로 증가합니다. 속성을 명시적으로 설정하여 용량을 Capacity 줄일 수 있습니다.

구현자 참고

이 기본 클래스는 구현자가 강력한 형식의 사용자 지정 컬렉션을 쉽게 만들 수 있도록 하기 위해 제공됩니다. 구현자는 자체 클래스를 만드는 대신 이 기본 클래스를 확장하는 것이 좋습니다.

생성자

CollectionBase()

기본 초기 용량을 사용하여 CollectionBase 클래스의 새 인스턴스를 초기화합니다.

CollectionBase(Int32)

지정한 용량을 사용하여 CollectionBase 클래스의 새 인스턴스를 초기화합니다.

속성

Capacity

CollectionBase에 포함될 수 있는 요소의 수를 가져오거나 설정합니다.

Count

CollectionBase 인스턴스에 포함된 요소 수를 가져옵니다. 이 속성은 재정의할 수 없습니다.

InnerList

ArrayList 인스턴스의 요소 목록을 포함하는 CollectionBase를 가져옵니다.

List

IList 인스턴스의 요소 목록을 포함하는 CollectionBase를 가져옵니다.

메서드

Clear()

CollectionBase 인스턴스에서 개체를 모두 제거합니다. 이 메서드는 재정의할 수 없습니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetEnumerator()

CollectionBase 인스턴스를 반복하는 열거자를 반환합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
OnClear()

CollectionBase 인스턴스의 콘텐츠를 지운 후에 추가로 사용자 지정 프로세스를 수행합니다.

OnClearComplete()

CollectionBase 인스턴스의 내용을 지운 후에 추가로 사용자 지정 프로세스를 수행합니다.

OnInsert(Int32, Object)

CollectionBase 인스턴스에 새 요소를 삽입하기 전에 추가로 사용자 지정 프로세스를 수행합니다.

OnInsertComplete(Int32, Object)

CollectionBase 인스턴스에 새 요소를 삽입한 후에 추가로 사용자 지정 프로세스를 수행합니다.

OnRemove(Int32, Object)

CollectionBase 인스턴스에서 요소를 제거할 때 추가로 사용자 지정 프로세스를 수행합니다.

OnRemoveComplete(Int32, Object)

CollectionBase 인스턴스에서 요소를 제거한 후에 추가로 사용자 지정 프로세스를 수행합니다.

OnSet(Int32, Object, Object)

CollectionBase 인스턴스에 값을 설정하기 전에 추가로 사용자 지정 프로세스를 수행합니다.

OnSetComplete(Int32, Object, Object)

CollectionBase 인스턴스에 값을 설정한 후에 추가로 사용자 지정 프로세스를 수행합니다.

OnValidate(Object)

값의 유효성을 검사할 때 추가로 사용자 지정 프로세스를 수행합니다.

RemoveAt(Int32)

CollectionBase 인스턴스의 지정한 인덱스에서 요소를 제거합니다. 이 메서드는 재정의할 수 없습니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

명시적 인터페이스 구현

ICollection.CopyTo(Array, Int32)

대상 배열의 지정된 인덱스에서 시작하여 전체 CollectionBase을 호환되는 1차원 Array에 복사합니다.

ICollection.IsSynchronized

CollectionBase에 대한 액세스가 동기화되어 스레드로부터 안전하게 보호되는지를 나타내는 값을 가져옵니다.

ICollection.SyncRoot

CollectionBase에 대한 액세스를 동기화하는 데 사용할 수 있는 개체를 가져옵니다.

IList.Add(Object)

개체를 CollectionBase의 끝 부분에 추가합니다.

IList.Contains(Object)

CollectionBase에 특정 요소가 들어 있는지 여부를 확인합니다.

IList.IndexOf(Object)

지정한 Object를 검색하고, 전체 CollectionBase 내에서 처음 나오는 0부터 시작하는 인덱스를 반환합니다.

IList.Insert(Int32, Object)

CollectionBase의 지정된 인덱스에 요소를 삽입합니다.

IList.IsFixedSize

CollectionBase의 크기가 고정되어 있는지 여부를 나타내는 값을 가져옵니다.

IList.IsReadOnly

CollectionBase가 읽기 전용인지 여부를 나타내는 값을 가져옵니다.

IList.Item[Int32]

지정한 인덱스에 있는 요소를 가져오거나 설정합니다.

IList.Remove(Object)

CollectionBase에서 맨 처음 발견되는 특정 개체를 제거합니다.

확장 메서드

Cast<TResult>(IEnumerable)

IEnumerable의 요소를 지정된 형식으로 캐스팅합니다.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable의 요소를 필터링합니다.

AsParallel(IEnumerable)

쿼리를 병렬화할 수 있도록 합니다.

AsQueryable(IEnumerable)

IEnumerableIQueryable로 변환합니다.

적용 대상

스레드 보안

공용 정적 (Shared Visual Basic의)이 형식의 멤버는 스레드로부터 안전 합니다. 인스턴스 구성원은 스레드로부터의 안전성이 보장되지 않습니다.

이 구현은 동기화된(스레드로부터 안전한) 래퍼를 CollectionBase제공하지 않지만 파생 클래스는 속성을 사용하여 SyncRoot 자체 동기화된 버전을 CollectionBase 만들 수 있습니다.

컬렉션을 열거 되지 본질적으로 스레드로부터 안전한 프로시저가 있습니다. 컬렉션이 동기화되어 있을 때 다른 스레드에서 해당 컬렉션을 수정할 수 있으므로 이렇게 되면 열거자에서 예외가 throw됩니다. 열거하는 동안 스레드로부터 안전을 보장하려면 전체 열거를 수행하는 동안 컬렉션을 잠그거나 다른 스레드에서 변경된 내용으로 인해 발생한 예외를 catch하면 됩니다.

추가 정보