C # yield return usage and parsing
This article is referenced from: http://www.jb51.net/article/54810.htm
Did not seriously understand yield this key word, and now encountered still do not understand, in order to later no longer for yield confusion, decided to study the use of yield and significance:
Yield from the literal understanding of the meaning of "abdication, yield", turn the bend to understand as "transfer of authority", that is, to give control to others, here is to meet the conditions in the set (if there is no filter, that is, all) the operation of the individual transferred to another object.
classProgram {Static voidMain (string[] args) { foreach(varIteminchFilterwithoutyield) {Console.WriteLine (item); } console.readkey (); } //declaring attributes, defining data sources Public Staticlist<int>Data {Get { return Newlist<int> () {1,2,3,4,5,6,7,8}; } } //declaration attribute, filter (yield not applicable) Public Staticienumerable<int>Filterwithoutyield {Get { varresult =Newlist<int>(); foreach(varIinchData) { if(I >4) result. ADD (i); } returnresult; } } }
You can see that if you don't use yield, you want to return all the trees that are greater than 4, going to another collection. In the case of yield, you don't have to be so troublesome:
// declaration property, filter ( Use yield) public static Ienumerable<int > Filterwithoutyield { get { foreach (var i in Data) { if (i > 4 ) yield return I; } } }
Why is that?
Discover with one-step debugging:
Although the output of the 2 methods is the same, the operating process is very different. The first method is to load the result set into memory and then traverse it, and the second method, each time the client calls, yields return a value to the client, which is "supply on demand".
The first method, the client invocation process is roughly:
With yield return, the client invocation process is roughly:
Why is the use of yield return guaranteed to start executing once every time the loop is traversed?
--Because the compiler generates a state machine to maintain the state of the iterator.
Simply put, when you want to get a collection of ienumerable<t> types instead of loading the data into memory at once, consider using yield return for "on demand".
C # yield return usage and parsing