Explanation:
Used in the iterator BlockProvide a value to the enumerated number object or send an iteration end signal. It is in the form of one of the following:
yield return expression;yield break;
Parameters
Expression
Calculate andObject value with enumerative number. ExpressionIt must be implicitly converted to the yield type of the iterator..
Remarks
The yield statement can only appear in the iterator block. This block can be used as a method, operator, or accessors. 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.
Yield statements cannot appear in anonymous methods. For more information, see the anonymous method (C # programming guide ).
When used together with expression, the yield return statement cannot appear in catch blocks or try blocks that contain one or more catch clauses. 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)
The yield statement is used. 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 ).
// 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; 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); } }}
Output
2 4 8 16 32 64 128 256
Before the yield keyword exists, we may need to use the following method to implement power:
public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; dim al as new arraylist(); while (counter++ < exponent) { result = result * number; al.add(result); } return al; }
From the above comparison, we can see that yield only partially simplifies our operations.