IEnumerable<T>.GetEnumerator IEnumerable<T>.GetEnumerator IEnumerable<T>.GetEnumerator IEnumerable<T>.GetEnumerator Method

정의

컬렉션을 반복하는 열거자를 반환합니다.Returns an enumerator that iterates through the collection.

public:
 System::Collections::Generic::IEnumerator<T> ^ GetEnumerator();
public System.Collections.Generic.IEnumerator<out T> GetEnumerator ();
abstract member GetEnumerator : unit -> System.Collections.Generic.IEnumerator<'T>
Public Function GetEnumerator () As IEnumerator(Of Out T)

반환

컬렉션을 반복하는 데 사용할 수 있는 열거자입니다.An enumerator that can be used to iterate through the collection.

예제

다음 예제에서는 구현 하는 방법에 설명 합니다 IEnumerable<T> 인터페이스를 사용 하 여 구현에는 LINQ 쿼리를 만듭니다.The following example demonstrates how to implement the IEnumerable<T> interface and uses that implementation to create a LINQ query. 구현 하는 경우 IEnumerable<T>를 구현 해야 IEnumerator<T> 또는 C#에 해당, 사용할 수 있습니다 합니다 생성 키워드입니다.When you implement IEnumerable<T>, you must also implement IEnumerator<T> or, for C# only, you can use the yield keyword. 구현 IEnumerator<T> 도 필요 IDisposable 구현 하려면이 예제에 표시 됩니다.Implementing IEnumerator<T> also requires IDisposable to be implemented, which you will see in this example.

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class App
{
    // Excercise the Iterator and show that it's more
    // performant.
    public static void Main()
    {
        TestStreamReaderEnumerable();
        Console.WriteLine("---");
        TestReadingFile();
    }

    public static void TestStreamReaderEnumerable()
	{
		// Check the memory before the iterator is used.
		long memoryBefore = GC.GetTotalMemory(true);
      IEnumerable<String> stringsFound;
		// Open a file with the StreamReaderEnumerable and check for a string.
      try {
         stringsFound =
               from line in new StreamReaderEnumerable(@"c:\temp\tempFile.txt")
               where line.Contains("string to search for")
               select line;
         Console.WriteLine("Found: " + stringsFound.Count());
      }
      catch (FileNotFoundException) {
         Console.WriteLine(@"This example requires a file named C:\temp\tempFile.txt.");
         return;
      }

		// Check the memory after the iterator and output it to the console.
		long memoryAfter = GC.GetTotalMemory(false);
		Console.WriteLine("Memory Used With Iterator = \t"
            + string.Format(((memoryAfter - memoryBefore) / 1000).ToString(), "n") + "kb");
	}

    public static void TestReadingFile()
	{
		long memoryBefore = GC.GetTotalMemory(true);
      StreamReader sr;
      try {
         sr = File.OpenText("c:\\temp\\tempFile.txt");
      }
      catch (FileNotFoundException) {
         Console.WriteLine(@"This example requires a file named C:\temp\tempFile.txt.");
         return;
      }

        // Add the file contents to a generic list of strings.
		List<string> fileContents = new List<string>();
		while (!sr.EndOfStream) {
			fileContents.Add(sr.ReadLine());
		}

		// Check for the string.
		var stringsFound = 
            from line in fileContents
            where line.Contains("string to search for")
            select line;

        sr.Close();
        Console.WriteLine("Found: " + stringsFound.Count());

		// Check the memory after when the iterator is not used, and output it to the console.
		long memoryAfter = GC.GetTotalMemory(false);
		Console.WriteLine("Memory Used Without Iterator = \t" + 
            string.Format(((memoryAfter - memoryBefore) / 1000).ToString(), "n") + "kb");
	}
}

// A custom class that implements IEnumerable(T). When you implement IEnumerable(T), 
// you must also implement IEnumerable and IEnumerator(T).
public class StreamReaderEnumerable : IEnumerable<string>
{
    private string _filePath;
    public StreamReaderEnumerable(string filePath)
    {
        _filePath = filePath;
    }

    // Must implement GetEnumerator, which returns a new StreamReaderEnumerator.
    public IEnumerator<string> GetEnumerator()
    {
        return new StreamReaderEnumerator(_filePath);
    }

    // Must also implement IEnumerable.GetEnumerator, but implement as a private method.
    private IEnumerator GetEnumerator1()
    {
        return this.GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator1();
    }
}

// When you implement IEnumerable(T), you must also implement IEnumerator(T), 
// which will walk through the contents of the file one line at a time.
// Implementing IEnumerator(T) requires that you implement IEnumerator and IDisposable.
public class StreamReaderEnumerator : IEnumerator<string>
{
    private StreamReader _sr;
    public StreamReaderEnumerator(string filePath)
    {
        _sr = new StreamReader(filePath);
    }

    private string _current;
    // Implement the IEnumerator(T).Current publicly, but implement 
    // IEnumerator.Current, which is also required, privately.
    public string Current
    {

        get
        {
            if (_sr == null || _current == null)
            {
                throw new InvalidOperationException();
            }

            return _current;
        }
    }

    private object Current1
    {

        get { return this.Current; }
    }

    object IEnumerator.Current
    {
        get { return Current1; }
    }

    // Implement MoveNext and Reset, which are required by IEnumerator.
    public bool MoveNext()
    {
        _current = _sr.ReadLine();
        if (_current == null)
            return false;
        return true;
    }

    public void Reset()
    {
        _sr.DiscardBufferedData();
        _sr.BaseStream.Seek(0, SeekOrigin.Begin);
        _current = null;
    }

    // Implement IDisposable, which is also implemented by IEnumerator(T).
    private bool disposedValue = false;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposedValue)
        {
            if (disposing)
            {
                // Dispose of managed resources.
            }
            _current = null;
            if (_sr != null) {
               _sr.Close();
               _sr.Dispose();
            }
        }

        this.disposedValue = true;
    }

     ~StreamReaderEnumerator()
    {
        Dispose(false);
    }
}
// This example displays output similar to the following:
//       Found: 2
//       Memory Used With Iterator =     33kb
//       ---
//       Found: 2
//       Memory Used Without Iterator =  206kb
Imports System.IO
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq

Public Module App
   ' Excercise the Iterator and show that it's more performant.
   Public Sub Main()
      TestStreamReaderEnumerable()
      Console.WriteLine("---")
      TestReadingFile()
   End Sub

   Public Sub TestStreamReaderEnumerable()
		' Check the memory before the iterator is used.
		Dim memoryBefore As Long = GC.GetTotalMemory(true)
      Dim stringsFound As IEnumerable(Of String)
		' Open a file with the StreamReaderEnumerable and check for a string.
      Try
         stringsFound =
               from line in new StreamReaderEnumerable("c:\temp\tempFile.txt")
               where line.Contains("string to search for")
               select line
         Console.WriteLine("Found: {0}", stringsFound.Count())
      Catch e As FileNotFoundException
         Console.WriteLine("This example requires a file named C:\temp\tempFile.txt.")
         Return
      End Try

		' Check the memory after the iterator and output it to the console.
		Dim memoryAfter As Long = GC.GetTotalMemory(false)
		Console.WriteLine("Memory Used with Iterator = {1}{0} kb",
                        (memoryAfter - memoryBefore)\1000, vbTab)
   End Sub

   Public Sub TestReadingFile()
		Dim memoryBefore As Long = GC.GetTotalMemory(true)
      Dim sr As StreamReader
      Try
         sr = File.OpenText("c:\temp\tempFile.txt")
      Catch e As FileNotFoundException
         Console.WriteLine("This example requires a file named C:\temp\tempFile.txt.")
         Return
      End Try

        ' Add the file contents to a generic list of strings.
		Dim fileContents As New List(Of String)()
		Do While Not sr.EndOfStream
			fileContents.Add(sr.ReadLine())
      Loop

		' Check for the string.
		Dim stringsFound =
            from line in fileContents
            where line.Contains("string to search for")
            select line

      sr.Close()
      Console.WriteLine("Found: {0}", stringsFound.Count())

		' Check the memory after when the iterator is not used, and output it to the console.
		Dim memoryAfter As Long = GC.GetTotalMemory(False)
		Console.WriteLine("Memory Used without Iterator = {1}{0} kb",
                        (memoryAfter - memoryBefore)\1000, vbTab)
   End Sub
End Module

' A custom class that implements IEnumerable(T). When you implement IEnumerable(T), 
' you must also implement IEnumerable and IEnumerator(T).
Public Class StreamReaderEnumerable : Implements IEnumerable(Of String)
    Private _filePath As String
    
    Public Sub New(filePath As String)
        _filePath = filePath
    End Sub

    ' Must implement GetEnumerator, which returns a new StreamReaderEnumerator.
    Public Function GetEnumerator() As IEnumerator(Of String) _
          Implements IEnumerable(Of String).GetEnumerator
        Return New StreamReaderEnumerator(_filePath)
    End Function

    ' Must also implement IEnumerable.GetEnumerator, but implement as a private method.
    Private Function GetEnumerator1() As IEnumerator _
          Implements IEnumerable.GetEnumerator
        Return Me.GetEnumerator()
    End Function
End Class

' When you implement IEnumerable(T), you must also implement IEnumerator(T), 
' which will walk through the contents of the file one line at a time.
' Implementing IEnumerator(T) requires that you implement IEnumerator and IDisposable.
Public Class StreamReaderEnumerator : Implements IEnumerator(Of String)
    Private _sr As StreamReader
    
    Public Sub New(filePath As String)
        _sr = New StreamReader(filePath)
    End Sub

    Private _current As String

    ' Implement the IEnumerator(T).Current Publicly, but implement 
    ' IEnumerator.Current, which is also required, privately.
    Public ReadOnly Property Current As String _
          Implements IEnumerator(Of String).Current
        Get
            If _sr Is Nothing OrElse _current Is Nothing
                Throw New InvalidOperationException()
            End If

            Return _current
        End Get
    End Property

    Private ReadOnly Property Current1 As Object _
          Implements IEnumerator.Current
        Get
           Return Me.Current
        End Get
    End Property

    ' Implement MoveNext and Reset, which are required by IEnumerator.
    Public Function MoveNext() As Boolean _
          Implements IEnumerator.MoveNext
        _current = _sr.ReadLine()
        if _current Is Nothing Then Return False

        Return True
    End Function

    Public Sub Reset() _
          Implements IEnumerator.Reset
        _sr.DiscardBufferedData()
        _sr.BaseStream.Seek(0, SeekOrigin.Begin)
        _current = Nothing
    End Sub

    ' Implement IDisposable, which is also implemented by IEnumerator(T).
    Private disposedValue As Boolean = False
    Public Sub Dispose() _
          Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' Dispose of managed resources.
            End If

            _current = Nothing
            If _sr IsNot Nothing Then
               _sr.Close()
               _sr.Dispose()
            End If
        End If

        Me.disposedValue = True
    End Sub

    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub
End Class
' This example displays output similar to the following:
'       Found: 2
'       Memory Used With Iterator =     33kb
'       ---
'       Found: 2
'       Memory Used Without Iterator =  206kb

다른 C# 예제를 구현 하는 방법에 설명 합니다 IEnumerable<T> 인터페이스를 참조 하십시오는 제네릭 샘플합니다.For another C# example that demonstrates how to implement the IEnumerable<T> interface, see the Generics Sample. 이 샘플 사용 합니다 yield 키워드를 구현 하는 대신 IEnumerator<T>합니다.This sample uses of the yield keyword instead of implementing IEnumerator<T>.

설명

반환 된 IEnumerator<T> 노출 하 여 컬렉션을 반복 하는 기능을 제공 된 Current 속성입니다. 열거자를 사용 하 여 컬렉션에서 데이터를 읽을 수 있지만 컬렉션을 수정할 수는 없습니다.The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property .You can use enumerators to read the data in a collection, but not to modify the collection.

처음에 열거자는 컬렉션의 첫 번째 요소 앞에 배치됩니다.Initially, the enumerator is positioned before the first element in the collection. 이 위치에서 Current는 정의되지 않습니다.At this position, Current is undefined. 따라서 호출 해야 합니다 MoveNext 해당 열거자의 값을 읽기 전에 컬렉션의 첫 번째 요소를 이동 하는 방법 Current합니다.Therefore, you must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current.

Current 될 때까지 동일한 개체를 반환 MoveNext 라고 다시 MoveNext 설정 Current 다음 요소에 있습니다.Current returns the same object until MoveNext is called again as MoveNext sets Current to the next element.

경우 MoveNext 열거자를 컬렉션의 끝 컬렉션의 마지막 요소 뒤에 배치 되는 전달 하 고 MoveNext 반환 false합니다.If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. 열거자가 있는 경우이 위치에 대 한 후속 호출은 MoveNext 반환할 수도 false합니다.When the enumerator is at this position, subsequent calls to MoveNext also return false. 마지막으로 호출 하는 경우 MoveNext 반환 false, Current 정의 되지 않습니다.If the last call to MoveNext returned false, Current is undefined. Current를 컬렉션의 첫 번째 요소로 다시 설정할 수 없으므로 대신 새 열거자 인스턴스를 만들어야 합니다.You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.

요소를 추가, 수정 또는 삭제 하는 등 컬렉션에 변경 내용이 열거자의 동작은 정의 되지 않습니다.If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined.

열거자는 없으므로 컬렉션에 대 한 단독 액세스 열거자의 컬렉션은 변경으로 들이 유효한 상태로 유지 합니다.An enumerator does not have exclusive access to the collection so an enumerator remains valid as long as the collection remains unchanged. 컬렉션 변경 되 면 열거자가 무효화 등 추가, 수정 또는 요소를 삭제 하 고 예기치 않은 결과가 발생할 수 있습니다.If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is invalidated and you may get unexpected results. 또한 컬렉션 열거는 스레드로부터 안전한 프로시저가 아닙니다.Also, enumerating a collection is not a thread-safe procedure. 스레드로부터의 안전성을 보장 하기 위해 열거자 동안 컬렉션을 잠글 하거나 컬렉션에 대해 동기화를 구현 해야 합니다.To guarantee thread-safety, you should lock the collection during enumerator or implement synchronization on the collection.

컬렉션의 기본 구현은 System.Collections.Generic 네임 스페이스 동기화 되지 않았습니다.Default implementations of collections in the System.Collections.Generic namespace aren't synchronized.

적용 대상

추가 정보