4.1 iterator Block
An iterator block is a block that can generate an ordered value sequence. The difference between an iterator block and a normal statement block is one or more yield statements.
The yield return Statement generates the next value of the iteration.
The yield break statement indicates that the iteration is complete.
As long as the return value type of the corresponding function member is an enumerative interface or an enumerative interface, an iterator block can be used as a method body, operator body, or accesser body.
The iterator block is not an independent element in the C # syntax. They are constrained by multiple factors and have a great impact on the semantics of function member declarations, but they are just blocks in syntax ).
When a function member uses an iterator block to implement the current situation, if the ref or out parameter is specified in the form parameter list of the function member, a compilation error will occur.
If the return statement appears in the iterator block, the compilation is incorrect (but the yield return Statement is allowed ).
If the iterator contains insecure context, a compilation error occurs. An iterator block must be defined in a secure context, even if its declaration is nested in an insecure context.
In the following example, the yield statement is used in the iterator block (the method Power (int number, int power.
When the Power method is called, it returns an enumerative object containing the number Power. Note that the return type of the Power method is IEnumerable (an iterator interface type ).
using System;using System.Collections;public class List{ public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } static void Main() { // Display powers of 2 up to the exponent 8: foreach (int i in Power(2, 8)) { Console.Write("{0} ", i); } }} 2 4 8 16 32 64 128 256