IEnumerable<T>.GetEnumerator Yöntem

Tanım

Toplulukta yinelenen bir numaralandırıcı döndürür.

C#
public System.Collections.Generic.IEnumerator<out T> GetEnumerator ();
C#
public System.Collections.Generic.IEnumerator<T> GetEnumerator ();

Döndürülenler

Koleksiyonda yinelemek için kullanılabilecek bir numaralandırıcı.

Örnekler

Aşağıdaki örnek, arabirimin IEnumerable<T> nasıl uygulanacağını gösterir ve linq sorgusu oluşturmak için bu uygulamayı kullanır. uyguladığınızda IEnumerable<T>, yalnızca C# için de uygulamanız IEnumerator<T> gerekir veya yield anahtar sözcüğünü kullanabilirsiniz. Uygulamanın IEnumerator<T> uygulanması için de bu örnekte göreceğiniz bir uygulama gerekir IDisposable .

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

public class App
{
    // Exercise 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(disposing: 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(disposing: false);
    }
}
// This example displays output similar to the following:
//       Found: 2
//       Memory Used With Iterator =     33kb
//       ---
//       Found: 2
//       Memory Used Without Iterator =  206kb

Açıklamalar

Döndürülen IEnumerator<T> , bir Current özelliğini açığa çıkartarak koleksiyonda yineleme olanağı sağlar. Bir koleksiyondaki verileri okumak için numaralandırıcıları kullanabilirsiniz, ancak koleksiyonu değiştiremezsiniz.

Başlangıçta, numaralandırıcı, koleksiyondaki ilk öğenin önüne yerleştirilir. Bu konumda Current tanımlanmamıştır. Bu nedenle, değerini Currentokumadan önce numaralandırıcıyı koleksiyonun ilk öğesine ilerletmek için yöntemini çağırmanız MoveNext gerekir.

Current, bir sonraki öğeye küme olarak MoveNextCurrent yeniden çağrılana kadar MoveNext aynı nesneyi döndürür.

Koleksiyonun sonunu geçerse MoveNext , numaralandırıcı koleksiyondaki son öğeden sonra konumlandırılır ve MoveNext döndürür false. Numaralandırıcı bu konumda olduğunda, sonraki çağrıları MoveNext da döndürür false. döndürülen son çağrı MoveNextfalseCurrent tanımlanmamışsa. Koleksiyonun ilk öğesine yeniden ayarlayamazsınız Current ; bunun yerine yeni bir numaralandırıcı örneği oluşturmanız gerekir.

Koleksiyonda öğe ekleme, değiştirme veya silme gibi değişiklikler yapılırsa, numaralandırıcının davranışı tanımsızdır.

Bir numaralandırıcının koleksiyona özel erişimi olmadığından, koleksiyon değişmediği sürece bir numaralandırıcı geçerli kalır. Koleksiyonda öğe ekleme, değiştirme veya silme gibi değişiklikler yapılırsa, numaralandırıcı geçersiz kılınmış olur ve beklenmeyen sonuçlar alabilirsiniz. Ayrıca, bir koleksiyonu listelemek iş parçacığı açısından güvenli bir yordam değildir. İş parçacığı güvenliğini garanti etmek için, numaralandırıcı sırasında koleksiyonu kilitlemeniz veya koleksiyonda eşitleme uygulamanız gerekir.

Ad alanında System.Collections.Generic koleksiyonların varsayılan uygulamaları eşitlenmez.

Şunlara uygulanır

Ürün Sürümler
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Ayrıca bkz.