C#学习基本概念之迭代器(Iterator)
2016-11-25 16:05
507 查看
An iterator can be used to step through collections such as lists and arrays.
An iterator method or
statement is reached, the current location in code is remembered.
Execution is restarted from that location the next time the iterator
function is called.
You consume an iterator from client code by using a foreach statement or by using a LINQ query.
In the following example, the first iteration of the
statement is reached. This iteration returns a value of 3, and the
current location in the iterator method is retained. On the next
iteration of the loop, execution in the iterator method continues from
where it left off, again stopping when it reaches a
statement. This iteration returns a value of 5, and the current
location in the iterator method is again retained. The loop completes
when the end of the iterator method is reached.
You can use a
Iterators were introduced in C# in Visual Studio 2005.
In this topic
Simple Iterator
Creating a Collection Class
Using Iterators with a Generic List
Syntax Information
Technical Implementation
Use of Iterators
For all examples in this topic except the Simple Iterator example, include using directives for the
Simple Iterator
The following example has a single
In the following example, the
The
The
In the following example, the
In addition to the generic GetEnumerator method, the non-generic GetEnumerator method must also be implemented. This is because IEnumerable<T> inherits from IEnumerable. The non-generic implementation defers to the generic implementation.
The
example uses named iterators to support various ways of iterating
through the same collection of data. These named iterators are the
The
An iterator can occur as a method or
An implicit conversion must exist from the expression type in the
In C#, an iterator method cannot have any
In C#, "yield" is not a reserved word and has special meaning only when it is used before a
Technical Implementation
Although
you write an iterator as a method, the compiler translates it into a
nested class that is, in effect, a state machine. This class keeps track
of the position of the iterator as long the
To
see what the compiler does, you can use the Ildasm.exe tool to view the
Microsoft intermediate language code that is generated for an iterator
method.
When you create an iterator for a class or struct, you do not have to implement the whole IEnumerator interface. When the compiler detects the iterator, it automatically generates the
On each successive iteration of the
Iterators do not support the IEnumerator.Reset method. To re-iterate from the start, you must obtain a new iterator.
For additional information, see the C# Language Specification.
Use of Iterators
Iterators enable you to maintain the simplicity of a
Modify the list sequence after the first
Avoid fully loading a large list before the first iteration of a
Encapsulate
building the list in the iterator. In the iterator method, you can
build the list and then yield each result in a loop.
备注:转载自:https://msdn.microsoft.com/zh-cn/library/mt639331.aspx
An iterator method or
getaccessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time. When a
yield return
statement is reached, the current location in code is remembered.
Execution is restarted from that location the next time the iterator
function is called.
You consume an iterator from client code by using a foreach statement or by using a LINQ query.
In the following example, the first iteration of the
foreachloop causes execution to proceed in the
SomeNumbersiterator method until the first
yield return
statement is reached. This iteration returns a value of 3, and the
current location in the iterator method is retained. 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. This iteration returns a value of 5, and the current
location in the iterator method is again retained. 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; }The return type of an iterator method or
getaccessor can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
You can use a
yield breakstatement to end the iteration.
Iterators were introduced in C# in Visual Studio 2005.
In this topic
Simple Iterator
Creating a Collection Class
Using Iterators with a Generic List
Syntax Information
Technical Implementation
Use of Iterators
For all examples in this topic except the Simple Iterator example, include using directives for the
System.Collectionsand
System.Collections.Genericnamespaces.
Simple Iterator
The following example has a single
yield returnstatement that is inside a for loop. In
Main, each iteration of the
foreachstatement body creates a call to the iterator function, which proceeds to the next
yield returnstatement.
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; } } }Creating a Collection Class
In the following example, the
DaysOfTheWeekclass implements the IEnumerable interface, which requires a GetEnumerator method. The compiler implicitly calls the
GetEnumeratormethod, which returns an IEnumerator.
The
GetEnumeratormethod returns each string one at a time by using the
yield returnstatement.
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]; } } }The following example creates a
Zooclass that contains a collection of animals.
The
foreachstatement that refers to the class instance (
theZoo) implicitly calls the
GetEnumeratormethod. The
foreachstatements that refer to the
Birdsand
Mammalsproperties use the
AnimalsForTypenamed 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; } } }Using Iterators with a Generic List
In the following example, the
Stack(Of T)generic class implements the IEnumerable<T> generic interface. The
Pushmethod assigns values to an array of type
T. The GetEnumerator method returns the array values by using the
yield returnstatement.
In addition to the generic GetEnumerator method, the non-generic GetEnumerator method must also be implemented. This is because IEnumerable<T> inherits from IEnumerable. The non-generic implementation defers to the generic implementation.
The
example uses named iterators to support various ways of iterating
through the same collection of data. These named iterators are the
TopToBottomand
BottomToTopproperties, and the
TopNmethod.
The
BottomToTopproperty uses an iterator in a
getaccessor.
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]; } } }Syntax Information
An iterator can occur as a method or
getaccessor. An iterator cannot occur in an event, instance constructor, static constructor, or static destructor.
An implicit conversion must exist from the expression type in the
yield returnstatement to the return type of the iterator.
In C#, an iterator method cannot have any
refor
outparameters.
In C#, "yield" is not a reserved word and has special meaning only when it is used before a
returnor
breakkeyword.
Technical Implementation
Although
you write an iterator as a method, the compiler translates it into a
nested class that is, in effect, a state machine. This class keeps track
of the position of the iterator as long the
foreachloop in the client code continues.
To
see what the compiler does, you can use the Ildasm.exe tool to view the
Microsoft intermediate language code that is generated for an iterator
method.
When you create an iterator for a class or struct, you do not have to implement the whole IEnumerator interface. When the compiler detects the iterator, it automatically generates the
Current,
MoveNext, and
Disposemethods of the IEnumerator or IEnumerator<T> interface.
On each successive iteration of the
foreachloop (or the direct call to
IEnumerator.MoveNext), the next iterator code body resumes after the previous
yield returnstatement. It then continues to the next
yield returnstatement until the end of the iterator body is reached, or until a
yield breakstatement is encountered.
Iterators do not support the IEnumerator.Reset method. To re-iterate from the start, you must obtain a new iterator.
For additional information, see the C# Language Specification.
Use of Iterators
Iterators enable you to maintain the simplicity of a
foreachloop when you need to use complex code to populate a list sequence. This can be useful when you want to do the following:
Modify the list sequence after the first
foreachloop iteration.
Avoid fully loading a large list before the first iteration of a
foreachloop. An example is a paged fetch to load a batch of table rows. Another example is the EnumerateFiles method, which implements iterators within the .NET Framework.
Encapsulate
building the list in the iterator. In the iterator method, you can
build the list and then yield each result in a loop.
备注:转载自:https://msdn.microsoft.com/zh-cn/library/mt639331.aspx
相关文章推荐
- c#学习笔记五 面向对象编程的基本概念 接口 继承和多态
- C#学习基本概念之常量
- C#学习基本概念之关键字--virtual
- C#学习基本概念之构造函数之四--静态构造函数
- C#学习基本概念之数据类型
- C#学习基本概念之传递值类型参数(一)
- C#学习基本概念之关键字--override
- C#学习基本概念之方法
- C#学习基本概念之构造函数之三--私有构造函数
- C#学习基本概念之结构与类
- C#学习基本概念之自动实现的属性
- C#学习基本概念之属性使用
- C#学习基本概念之关键字--volatile(不稳定)
- 第一天,第一个C#程序,学习C#基本语法。掌握命名空间、类、变量、方法等基本概念。
- C#学习基本概念之访问修饰符
- C#学习基本概念之接口属性
- C#学习基本概念之属性与索引器之间的比较
- C#学习基本概念之构造函数之五---编写复制构造函数
- C#学习基本概念之生存期、可访问域、可访问性级别
- C#学习基本概念之构造函数之二(实例构造函数)