Introduction: http://www.cnblogs.com/yank/archive/2011/07/02/2096240.html
Yield Introduction
The yield keyword instructs the compiler that its method is an iterator block.
In the iterator block,YieldKeyword andReturnKeyword used in combination to provide the enumerator objectA return value, for example, inForeachThe value returned in each loop of the statement.YieldThe keyword can also beBreakCombined Use, indicates that the iteration ends.
1. Yield return <expression>; In the yield return statementExpressionReturn the result to the enumerated object as a value;ExpressionIt must be implicitly converted to an iterator of the yield type.
2. Yield break;
InYield breakThe control is returned to the caller of the iterator unconditionally.Ienumerator. movenextMethod (or its corresponding genericSystem. Collections. Generic. ienumerable <t>) OrDisposeMethod.
Yield restrictions
YieldThe statement can only appear inIteratorBlock, which can be implemented as the subject of methods, operators, 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.
The yield return statement cannot be placed in any position in the try-Catch Block.This statement can be placed in try blocks followed by finally blocks.
Yield break statements can be placed in try blocks or catch blocks, but not in finally blocks.
YieldThe statement cannot appear in the anonymous method.For more information, seeAnonymous method (C # programming guide).
When andExpressionWhen used together,Yield returnThe statement cannot appear inCatchBlock or contains one or moreCatchClauseTryBlock.
Yield usage example
Public ClassList
{
//Using system. collections;
PublicStaticIenumerable power (IntNumber,IntExponent)
{
IntCounter=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(IntIInPower (2,8))
{
Console. Write ("{0}", I );
}
}
}
/*Output:
2 4 8 16 32 64 128 256
*/