The iterator block is used to provide a value to the enumerated number object or send an iteration end signal. It is in the form of one of the following:
| |
|
YieldReturn <expression>;YieldBreak; |
Remarks
Calculates the expression and returns it as an enumerated number object value;ExpressionIt must be implicitly converted to an iteratorYieldType.
YieldThe statement can only appear inIteratorBlock. These methods, operators, or accessors are subject to the following constraints:
-
Insecure blocks are not allowed.
-
The parameters of methods, operators, or accessors cannot be ref or out.
YieldThe statement cannot appear in the anonymous method. For more information, see the anonymous method (C # programming guide ).
When andExpressionWhen used together,YieldReturnThe statement cannot appear inCatchBlock or contains one or moreCatchClauseTryBlock. For more information, see Exception Handling statements (C # reference ).
Example
In the following example, the iterator block (here is the methodPower (INT number, int power)).YieldStatement. WhenPowerMethod. Note:PowerThe return type of the method isIenumerable(An iterator interface type ).
| |
Copy code |
//Yield-Example. csusing 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;YieldReturn result ;}} static void main () {// display powers of 2 up to the exponent 8: foreach (int I in power (2, 8) {console. write ("{0}", I );}}} |