Yield instructs the compiler that its method is an iterator block.
Yield is not a keyword in. net, so we can use it for variable names. However, yield return and yield break are keywords.
Yield return
Yield return is an implementation of the iterator pattern mode. It can make objects that are not an iterative set into an iterative set.
Static Void Main ( String [] ARGs)
{
Foreach (VAR item In Getnums ())
{
Console. writeline (item );
}
}
Static Ienumerable getnums ()
{
Yield Return " Start " ;
Yield Return 1 ;
Yield Return 2 ;
Yield Return 3 ;
Yield Return 4 ;
Yield Return " End " ;
}
Note:
- Yield return is followed by an expression, which must be converted to the type used by the iterator;
- Yield return can only be used in the iterator block. This iterator block can be placed in the method body, in the operation function, or in the accessors (attribute method );
- Yield return cannot be in unsafe blocks (unsafe );
- The parameters of methods, operators, or accessors cannot be ref or out;
- Yield return cannot appear in catch statements or in try blocks with one or more catch clauses;
- Yield statements cannot appear in anonymous methods.
Yield break
For some reason, the yield break keyword group can be used before the final element is returned.
Static Void Main ( String [] ARGs)
{
Foreach (VAR item In Getnums ())
{
Console. writeline (item );
}
}
Static Ienumerable getnums ()
{
Yield Return " Start " ;
Yield Return 1 ;
Yield Return 2 ;
Yield Break ;
Yield Return 3 ;
Yield Return 4 ;
Yield Return " End " ;
}
In this way, no information under 2 will be output.
Summary
The key group yield return and yield break are introduced in. NET 2.0. Yield return is used to create an automatically generated and typed enumerator, while yield break is used to terminate iteration before reaching the final element. They are also very useful in LINQ queries. The key to the latency mechanism of LINQ is on yield.
MoreArticleYou can see: (mark)
Http://kb.cnblogs.com/page/42581/
Http://www.cnblogs.com/jeffreyzhao/archive/2010/01/26/decompile-methods-with-yield-manually.html