Yield is the syntactic sugar that C # implements to simplify traversal operations. Use the yield keyword in a statement to indicate that the method, operator, or get accessor where the keyword is located is an iterator. There are two kinds of forms:
yield return <expression>; yield break;
This is a more clear example:
Static voidMain (string[] args) { foreach(intIinchPower (2,8) {Console.Write ("{0}", i); } //Output:2 4 8Console.readkey ();} Public StaticSystem.Collections.IEnumerable Power (intNumberintexponent) { intresult =1; for(inti =0; i < exponent; i++) {result= result *Number ; yield returnresult; }}
Here, you use the yield return Returns each element node.Use foreach Statement or a LINQ query, the iterator method is used.foreach Loop calls the iterator method. > foreach loop. yield return statement is reached in the iterator method, when yield return statement is in the iterator method, expression returns, and, The current position of the code is reserved. The next time the iterator function is called, execution restarts from that location. By debugging, we can see that the code executes in the following order:
The order of the marks in this diagram may be a bit abstract, I wonder if you can understand? ~~~
In addition there is a yield break, which means ending the iteration and jumping out of the loop. Do not understand, see examples:
Static voidMain (string[] args) { foreach(intIinchPower (2,8) {Console.Write ("{0}", i); } //Output:2 4 8Console.readkey ();} Public StaticSystem.Collections.IEnumerable Power (intNumberintexponent) { intresult =1; for(inti =0; i < exponent; i++) {result= result *Number ; if(i = =4) yield Break; yield returnresult; }}Reference documents
- Https://msdn.microsoft.com/library/9k7k7cf0%28v=vs.110%29.aspx
- Http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html
- Http://www.cnblogs.com/CareySon/archive/2009/12/16/1625469.html
C # Keywords: yield