C # yield return usage and analysis,
C # yield return usage and Analysis
Reference: http://www.jb51.net/article/54810.htm
I didn't really understand the yield keyword at the beginning, but now I still don't understand it. I decided to study the usage and significance of yield for the sake of not being confused about yield in the future:
Yield literally refers to the meaning of "Return, give in". After turning it around, it will be understood as "permission transfer", that is, giving control to others, here, the individual operations in the set that meet the conditions (if there is no filtering condition, it is all) are transferred to another object.
Class Program {static void Main (string [] args) {foreach (var item in FilterWithoutYield) {Console. writeLine (item);} Console. readKey () ;}// declare the attribute and define the Data source public static List <int> Data {get {return new List <int>, 7,8 };}// declare attributes. The filter (not applicable to yield) public static IEnumerable <int> FilterWithoutYield {get {var result = new List <int> (); foreach (var I in Data) {if (I> 4) result. add (I) ;}return result ;}}}
We can see that if yield is not used, to return all the trees greater than 4, we need to go to another set. Yield does not have to be so troublesome:
// Declare attributes, filter (use yield) public static IEnumerable <int> FilterWithoutYield {get {foreach (var I in Data) {if (I> 4) yield return I ;}}}
Why?
Through one-step debugging, we found that:
Although the output results of the two methods are the same, the operation process is quite different. The first method is to load all the result sets to the memory and traverse them. The second method is to return a value to the client every time the client calls yield return, which is "supplied on demand ".
In the first method, the client call process is roughly as follows:
When yield return is used, the client call process is roughly as follows:
Why can I use yield return to ensure that execution starts from the previous stopped place during each loop traversal?
-- The compiler generates a state machine to maintain the iterator state.
To put it simply, if you want to obtain a set of IEnumerable <T> types instead of loading data to the memory at a time, you can use yield return to implement "On-Demand Supply ".