Iteratory (C#)Iterators (C#)
Iterator może służyć do przechodzenia między kolekcjami, takimi jak listy i tablice.An iterator can be used to step through collections such as lists and arrays.
Metoda iteratora lub get
akcesor wykonuje niestandardową iterację w kolekcji.An iterator method or get
accessor performs a custom iteration over a collection. Metoda iterator używa instrukcji yield return , aby zwrócić każdy element po jednym naraz.An iterator method uses the yield return statement to return each element one at a time. Po yield return
osiągnięciu instrukcji zostanie zapamiętana bieżąca lokalizacja w kodzie.When a yield return
statement is reached, the current location in code is remembered. Wykonanie jest uruchamiane ponownie z tej lokalizacji przy następnym wywołaniu funkcji iteratora.Execution is restarted from that location the next time the iterator function is called.
Iterator z kodu klienta jest używany przy użyciu instrukcji foreach lub zapytania LINQ.You consume an iterator from client code by using a foreach statement or by using a LINQ query.
W poniższym przykładzie pierwsza iteracja pętli powoduje, że foreach
wykonywanie jest wykonywane w SomeNumbers
metodzie iteratora do momentu yield return
osiągnięcia pierwszej instrukcji.In the following example, the first iteration of the foreach
loop causes execution to proceed in the SomeNumbers
iterator method until the first yield return
statement is reached. Ta iteracja zwraca wartość 3, a bieżąca lokalizacja w metodzie iteratora jest zachowywana.This iteration returns a value of 3, and the current location in the iterator method is retained. W następnej iteracji pętli wykonywanie w metodzie iteratora jest kontynuowane od miejsca, w którym została pozostawiona, po osiągnięciu yield return
instrukcji.On the next iteration of the loop, execution in the iterator method continues from where it left off, again stopping when it reaches a yield return
statement. Ta iteracja zwraca wartość 5, a bieżąca lokalizacja w metodzie iteratora jest zachowywana ponownie.This iteration returns a value of 5, and the current location in the iterator method is again retained. Pętla kończy się, gdy zostanie osiągnięty koniec metody iteratora.The loop completes when the end of the iterator method is reached.
static void Main()
{
foreach (int number in SomeNumbers())
{
Console.Write(number.ToString() + " ");
}
// Output: 3 5 8
Console.ReadKey();
}
public static System.Collections.IEnumerable SomeNumbers()
{
yield return 3;
yield return 5;
yield return 8;
}
Typem zwracanym metody iteratora lub get
akcesora może być IEnumerable , IEnumerable<T> , IEnumerator , lub IEnumerator<T> .The return type of an iterator method or get
accessor can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
Możesz użyć instrukcji, yield break
Aby zakończyć iterację.You can use a yield break
statement to end the iteration.
Uwaga
We wszystkich przykładach w tym temacie oprócz prostego przykładu iteratora using należy uwzględnić dyrektywy using System.Collections
dla System.Collections.Generic
przestrzeni nazw i.For all examples in this topic except the Simple Iterator example, include using directives for the System.Collections
and System.Collections.Generic
namespaces.
Iterator prostySimple Iterator
Poniższy przykład zawiera pojedynczą yield return
instrukcję, która znajduje się wewnątrz pętli for .The following example has a single yield return
statement that is inside a for loop. W programie Main
każda iteracja foreach
treści instrukcji tworzy wywołanie funkcji iteratora, która przechodzi do następnej yield return
instrukcji.In Main
, each iteration of the foreach
statement body creates a call to the iterator function, which proceeds to the next yield return
statement.
static void Main()
{
foreach (int number in EvenSequence(5, 18))
{
Console.Write(number.ToString() + " ");
}
// Output: 6 8 10 12 14 16 18
Console.ReadKey();
}
public static System.Collections.Generic.IEnumerable<int>
EvenSequence(int firstNumber, int lastNumber)
{
// Yield even numbers in the range.
for (int number = firstNumber; number <= lastNumber; number++)
{
if (number % 2 == 0)
{
yield return number;
}
}
}
Tworzenie klasy kolekcjiCreating a Collection Class
W poniższym przykładzie DaysOfTheWeek
Klasa implementuje IEnumerable interfejs, który wymaga GetEnumerator metody.In the following example, the DaysOfTheWeek
class implements the IEnumerable interface, which requires a GetEnumerator method. Kompilator niejawnie wywołuje GetEnumerator
metodę, która zwraca IEnumerator .The compiler implicitly calls the GetEnumerator
method, which returns an IEnumerator.
GetEnumerator
Metoda zwraca każdy ciąg pojedynczo przy użyciu yield return
instrukcji.The GetEnumerator
method returns each string one at a time by using the yield return
statement.
static void Main()
{
DaysOfTheWeek days = new DaysOfTheWeek();
foreach (string day in days)
{
Console.Write(day + " ");
}
// Output: Sun Mon Tue Wed Thu Fri Sat
Console.ReadKey();
}
public class DaysOfTheWeek : IEnumerable
{
private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
public IEnumerator GetEnumerator()
{
for (int index = 0; index < days.Length; index++)
{
// Yield each day of the week.
yield return days[index];
}
}
}
Poniższy przykład tworzy Zoo
klasę, która zawiera kolekcję zwierząt.The following example creates a Zoo
class that contains a collection of animals.
foreach
Instrukcja odwołująca się do wystąpienia klasy ( theZoo
) niejawnie wywołuje GetEnumerator
metodę.The foreach
statement that refers to the class instance (theZoo
) implicitly calls the GetEnumerator
method. foreach
Instrukcje odwołujące się do Birds
Mammals
właściwości i używają AnimalsForType
nazwanego metody iteratora.The foreach
statements that refer to the Birds
and Mammals
properties use the AnimalsForType
named iterator method.
static void Main()
{
Zoo theZoo = new Zoo();
theZoo.AddMammal("Whale");
theZoo.AddMammal("Rhinoceros");
theZoo.AddBird("Penguin");
theZoo.AddBird("Warbler");
foreach (string name in theZoo)
{
Console.Write(name + " ");
}
Console.WriteLine();
// Output: Whale Rhinoceros Penguin Warbler
foreach (string name in theZoo.Birds)
{
Console.Write(name + " ");
}
Console.WriteLine();
// Output: Penguin Warbler
foreach (string name in theZoo.Mammals)
{
Console.Write(name + " ");
}
Console.WriteLine();
// Output: Whale Rhinoceros
Console.ReadKey();
}
public class Zoo : IEnumerable
{
// Private members.
private List<Animal> animals = new List<Animal>();
// Public methods.
public void AddMammal(string name)
{
animals.Add(new Animal { Name = name, Type = Animal.TypeEnum.Mammal });
}
public void AddBird(string name)
{
animals.Add(new Animal { Name = name, Type = Animal.TypeEnum.Bird });
}
public IEnumerator GetEnumerator()
{
foreach (Animal theAnimal in animals)
{
yield return theAnimal.Name;
}
}
// Public members.
public IEnumerable Mammals
{
get { return AnimalsForType(Animal.TypeEnum.Mammal); }
}
public IEnumerable Birds
{
get { return AnimalsForType(Animal.TypeEnum.Bird); }
}
// Private methods.
private IEnumerable AnimalsForType(Animal.TypeEnum type)
{
foreach (Animal theAnimal in animals)
{
if (theAnimal.Type == type)
{
yield return theAnimal.Name;
}
}
}
// Private class.
private class Animal
{
public enum TypeEnum { Bird, Mammal }
public string Name { get; set; }
public TypeEnum Type { get; set; }
}
}
Używanie iteratorów z listą ogólnąUsing Iterators with a Generic List
W poniższym przykładzie Stack<T> Klasa generyczna implementuje IEnumerable<T> interfejs generyczny.In the following example, the Stack<T> generic class implements the IEnumerable<T> generic interface. PushMetoda przypisuje wartości do tablicy typu T
.The Push method assigns values to an array of type T
. GetEnumeratorMetoda zwraca wartości tablicy przy użyciu yield return
instrukcji.The GetEnumerator method returns the array values by using the yield return
statement.
Oprócz GetEnumerator metody ogólnej GetEnumerator należy również zaimplementować metodę nierodzajową.In addition to the generic GetEnumerator method, the non-generic GetEnumerator method must also be implemented. Wynika to z faktu, że IEnumerable<T> dziedziczy z IEnumerable .This is because IEnumerable<T> inherits from IEnumerable. Implementacja nieogólna odłożenia do ogólnej implementacji.The non-generic implementation defers to the generic implementation.
W przykładzie używa się nazwanych iteratorów do obsługi różnych sposobów iterowania za pośrednictwem tej samej kolekcji danych.The example uses named iterators to support various ways of iterating through the same collection of data. Te nazwane Iteratory to TopToBottom
właściwości i i BottomToTop
TopN
Metoda.These named iterators are the TopToBottom
and BottomToTop
properties, and the TopN
method.
BottomToTop
Właściwość używa iteratora w get
metodzie dostępu.The BottomToTop
property uses an iterator in a get
accessor.
static void Main()
{
Stack<int> theStack = new Stack<int>();
// Add items to the stack.
for (int number = 0; number <= 9; number++)
{
theStack.Push(number);
}
// Retrieve items from the stack.
// foreach is allowed because theStack implements IEnumerable<int>.
foreach (int number in theStack)
{
Console.Write("{0} ", number);
}
Console.WriteLine();
// Output: 9 8 7 6 5 4 3 2 1 0
// foreach is allowed, because theStack.TopToBottom returns IEnumerable(Of Integer).
foreach (int number in theStack.TopToBottom)
{
Console.Write("{0} ", number);
}
Console.WriteLine();
// Output: 9 8 7 6 5 4 3 2 1 0
foreach (int number in theStack.BottomToTop)
{
Console.Write("{0} ", number);
}
Console.WriteLine();
// Output: 0 1 2 3 4 5 6 7 8 9
foreach (int number in theStack.TopN(7))
{
Console.Write("{0} ", number);
}
Console.WriteLine();
// Output: 9 8 7 6 5 4 3
Console.ReadKey();
}
public class Stack<T> : IEnumerable<T>
{
private T[] values = new T[100];
private int top = 0;
public void Push(T t)
{
values[top] = t;
top++;
}
public T Pop()
{
top--;
return values[top];
}
// This method implements the GetEnumerator method. It allows
// an instance of the class to be used in a foreach statement.
public IEnumerator<T> GetEnumerator()
{
for (int index = top - 1; index >= 0; index--)
{
yield return values[index];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerable<T> TopToBottom
{
get { return this; }
}
public IEnumerable<T> BottomToTop
{
get
{
for (int index = 0; index <= top - 1; index++)
{
yield return values[index];
}
}
}
public IEnumerable<T> TopN(int itemsFromTop)
{
// Return less than itemsFromTop if necessary.
int startIndex = itemsFromTop >= top ? 0 : top - itemsFromTop;
for (int index = top - 1; index >= startIndex; index--)
{
yield return values[index];
}
}
}
Informacje o składniSyntax Information
Iterator może wystąpić jako metoda lub get
akcesor.An iterator can occur as a method or get
accessor. Iterator nie może wystąpić w zdarzeniu, konstruktorze wystąpienia, konstruktorze statycznym lub niestatycznego finalizatora.An iterator cannot occur in an event, instance constructor, static constructor, or static finalizer.
Niejawna konwersja musi istnieć z typu wyrażenia w yield return
instrukcji do argumentu typu IEnumerable<T>
zwracanego przez iterator.An implicit conversion must exist from the expression type in the yield return
statement to the type argument for the IEnumerable<T>
returned by the iterator.
W języku C# Metoda iteratora nie może mieć in
żadnych ref
parametrów,, ani out
.In C#, an iterator method cannot have any in
, ref
, or out
parameters.
W języku C#, yield
nie jest słowem zastrzeżonym i ma specjalne znaczenie tylko wtedy, gdy jest używany return
przed break
słowem kluczowym or.In C#, yield
is not a reserved word and has special meaning only when it is used before a return
or break
keyword.
Realizacja technicznaTechnical Implementation
Chociaż należy napisać iterator jako metodę, kompilator tłumaczy go na zagnieżdżoną klasę, która jest, w efekcie, komputera stanu.Although you write an iterator as a method, the compiler translates it into a nested class that is, in effect, a state machine. Ta klasa śledzi pozycję iteratora, tak długo foreach
Pętla w kodzie klienta jest kontynuowana.This class keeps track of the position of the iterator as long the foreach
loop in the client code continues.
Aby zobaczyć, co robi kompilator, możesz użyć narzędzia Ildasm.exe, aby wyświetlić kod języka pośredniego firmy Microsoft, który jest generowany dla metody iterator.To see what the compiler does, you can use the Ildasm.exe tool to view the Microsoft intermediate language code that's generated for an iterator method.
Podczas tworzenia iteratora dla klasy lub strukturynie trzeba implementować całego IEnumerator interfejsu.When you create an iterator for a class or struct, you don't have to implement the whole IEnumerator interface. Gdy kompilator wykryje iterator, automatycznie generuje Current
MoveNext
metody,, i Dispose
IEnumerator IEnumerator<T> interfejsu.When the compiler detects the iterator, it automatically generates the Current
, MoveNext
, and Dispose
methods of the IEnumerator or IEnumerator<T> interface.
Dla każdej kolejnej iteracji foreach
pętli (lub bezpośredniego wywołania do IEnumerator.MoveNext
) Następna treść kodu iteratora zostanie wznowiona po poprzedniej yield return
instrukcji.On each successive iteration of the foreach
loop (or the direct call to IEnumerator.MoveNext
), the next iterator code body resumes after the previous yield return
statement. Następnie przechodzi do następnej yield return
instrukcji do momentu osiągnięcia końca treści iteratora lub do momentu yield break
napotkania instrukcji.It then continues to the next yield return
statement until the end of the iterator body is reached, or until a yield break
statement is encountered.
Iteratory nie obsługują IEnumerator.Reset metody.Iterators don't support the IEnumerator.Reset method. Aby wykonać ponowną iterację od początku, należy uzyskać nowy iterator.To reiterate from the start, you must obtain a new iterator. Wywołanie Reset iteratora zwróconego przez metodę iteratora generuje NotSupportedException .Calling Reset on the iterator returned by an iterator method throws a NotSupportedException.
Aby uzyskać dodatkowe informacje, zobacz specyfikację języka C#.For additional information, see the C# Language Specification.
Użycie iteratorówUse of Iterators
Iteratory umożliwiają zachowanie prostoty foreach
pętli, gdy trzeba użyć kodu złożonego, aby wypełnić sekwencję listy.Iterators enable you to maintain the simplicity of a foreach
loop when you need to use complex code to populate a list sequence. Może to być przydatne, gdy chcesz wykonać następujące czynności:This can be useful when you want to do the following:
Zmodyfikuj sekwencję list po pierwszej
foreach
iteracji pętli.Modify the list sequence after the firstforeach
loop iteration.Unikaj całkowitego ładowania dużej listy przed pierwszą iteracją
foreach
pętli.Avoid fully loading a large list before the first iteration of aforeach
loop. Przykładem jest pobieranie stronicowane w celu załadowania partii wierszy tabeli.An example is a paged fetch to load a batch of table rows. Innym przykładem jest EnumerateFiles Metoda, która implementuje Iteratory w programie .NET.Another example is the EnumerateFiles method, which implements iterators in .NET.Hermetyzuje Kompilowanie listy w iterator.Encapsulate building the list in the iterator. W metodzie iteratora można skompilować listę, a następnie dać każdy wynik w pętli.In the iterator method, you can build the list and then yield each result in a loop.