이 항목은 아직 평가되지 않았습니다.- 이 항목 평가

CollectionBase.GetEnumerator 메서드

업데이트: 2007년 11월

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

네임스페이스:  System.Collections
어셈블리:  mscorlib(mscorlib.dll)

public IEnumerator GetEnumerator()
public final IEnumerator GetEnumerator()
public final function GetEnumerator() : IEnumerator

반환 값

형식: System.Collections.IEnumerator

CollectionBase 인스턴스의 IEnumerator입니다.

구현

IEnumerable.GetEnumerator()
vb#c#

C# 언어의 foreach 문(Visual Basic에서는 for each)은 열거자를 덜 복잡하게 표시합니다. 따라서 열거자를 직접 조작하는 것보다는 foreach를 사용하는 것이 좋습니다.

열거자는 컬렉션에 있는 데이터를 읽는 데 사용할 수 있지만 내부 컬렉션을 수정하는 데에는 사용할 수 없습니다.

처음에는 열거자가 컬렉션의 첫 번째 요소 앞에 배치됩니다. 그러면 Reset은 열거자를 이 위치로 다시 가져옵니다. 이 위치에서 Current를 호출하면 예외가 throw됩니다. 따라서 Current의 값을 읽기 전에 MoveNext를 호출하여 열거자를 해당 컬렉션의 첫 번째 요소로 보내야 합니다.

Current에서는 MoveNext 또는 Reset이 호출될 때까지 동일한 개체를 반환합니다. MoveNextCurrent를 다음 요소로 설정합니다.

MoveNext가 컬렉션의 끝을 지나게 되면 열거자는 컬렉션의 마지막 요소 뒤에 배치되고, MoveNextfalse를 반환합니다. 열거자가 이 위치에 있는 경우 MoveNext에 대한 후속 호출 또한 false를 반환합니다. MoveNext에 대한 마지막 호출에서 false가 반환된 경우 Current를 호출하면 예외가 throw됩니다. Current를 해당 컬렉션의 첫 번째 요소로 다시 설정하려면 Reset을 호출한 다음 MoveNext를 호출하면 됩니다.

열거자는 컬렉션이 변경되지 않은 상태로 유지되는 한 유효합니다. 그러나 요소를 추가, 수정, 삭제하는 등 컬렉션을 변경하면 열거자는 더 이상 유효하지 않으며(복구할 수 없음) 다음에 MoveNext 또는 Reset을 호출하면 InvalidOperationException이 throw됩니다. MoveNextCurrent 사이에서 컬렉션이 수정되면 Current는 열거자가 이미 유효하지 않더라도 자신이 설정한 요소를 반환합니다.

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

GetEnumerator 메서드는 기본적으로 COM 클라이언트에 표시되지 않지만 CollectionBase 클래스를 상속하면 이 메서드를 노출할 수 있습니다. 그러나 이 경우 COM 클라이언트에 예기치 않은 동작이 발생할 수 있습니다.

이 메서드는 O(1) 연산입니다.

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

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

*/



import System.* ;
import System.Collections.*;
import System.Collections.CollectionBase.*;

public class Int16Collection extends CollectionBase
{
    /** @property 
     */
    public short get_Value(int index)
    {
        short s = System.Convert.ToInt16(get_List().get_Item(index));
        return(s) ; 
    } //get_Value

    /** @property 
     */
    public void set_Value(int index,short value)
    {
        get_List().set_Item(index, (Int16)value);
    } //set_Value

    public int Add(short value) 
    {
        return get_List().Add((Int16)value);
    } //Add

    public int IndexOf(short value)
    {
        return get_List().IndexOf((Int16)value);
    } //IndexOf

    public void Insert(int index, short value) 
    {
        get_List().Insert(index, (Int16)value);
    } //Insert

    public void Remove(short value) 
    {
        get_List().Remove((Int16)value);
    } //Remove

    public boolean Contains(short value) 
    {
        // If value is not of type Int16, this will return false.
        return get_List().Contains((Int16)value);
    } //Contains

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

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

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

    protected   void OnValidate(Object value) 
    {
        if ( value.GetType() != Type.GetType("System.Int16")  ) {
            throw new ArgumentException("value must be of type Int16.", 
                "value");
        }
    } //OnValidate
} //Int16Collection

public class SamplesCollectionBase
{
    public static void main(String[] args)
    {
        // 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 for.
        Console.WriteLine("Contents of the collection (using for):");
        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}", 
            (System.Boolean)myI16.Contains((Int16)3));
        Console.WriteLine("2 is at index {0}.", 
            (Int16)myI16.IndexOf((Int16)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 .set_Item( 4 ,(Int16)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);
   } //main

   // Uses the Count property and the Item property.
    public static void PrintIndexAndValues(Int16Collection myCol) 
    {
        for(int i = 0; i < myCol.get_Count(); i++) {
            Console.WriteLine("   [{0}]:   {1}", (Int32)i, 
                myCol.get_Item(i));
        } 
        Console.WriteLine();
    } //PrintIndexAndValues

    // Uses the for statement which hides the complexity of the enumerator.
    // NOTE: The for statement is the preferred way of enumerating the contents 
    // of a collection.
    public static void PrintValues1(Int16Collection myCol) 
    {
        for (int iCtr = 0; iCtr < myCol.get_Count(); iCtr++) {
            Console.WriteLine("   {0}", myCol.get_Item(iCtr));
        }
        Console.WriteLine();
    } //PrintValues1

    // Uses the enumerator. 
    // NOTE: The for 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.get_Current());
        }
        Console.WriteLine();
    } //PrintValues2
} //SamplesCollectionBase

/* 
Contents of the collection (using for):
   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

*/



Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

.NET Framework 및 .NET Compact Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.

.NET Framework

3.5, 3.0, 2.0, 1.1, 1.0에서 지원

.NET Compact Framework

3.5, 2.0, 1.0에서 지원

XNA Framework

2.0, 1.0에서 지원
이 정보가 도움이 되었습니까?
(1500자 남음)

커뮤니티 추가 항목

추가
© 2013 Microsoft. All rights reserved.