Yield keyword before used less, but in the process of doing project development also encountered, at that time a bit confused, and by the way research study a bit, the following is a personal understanding, not to the place welcome to shoot Bricks! Here's the crap, on the code:
class program{ static void Main (string [] (args) { string [] STRs = new Span style= "color: #0000ff;" >string [] { 1 ", " 2 , " 3 , " 4 };
foreach (vargetints (STRs))
{
" ---- " + Item);
Console.readkey ();
Static ienumerable<int> getints (string[] strs)
{
foreach (var in STRs)
{
// Here's an extension method. yield return
}
}
}
Execution Result:
Brief description: (1) Normal when we return the value, you can write the Getints method as a list method to accept the return, the Code multiline List.add () does not say, after the use of Yeild return straight line of code back, the code is much reduced; you can understand it as a container. ; (Note: The understanding here is incorrect)
Here's a good understanding:
To retrofit the above code:
1 Static voidMain (string[] args)2 {3 string[] STRs =New string[] {"1","2","3","4" };4 5 foreach(varIteminchgetints (STRs))6 {7 if (item>2) 8 {9 break;10 } OneConsole.WriteLine (item. GetType () +"----"+item); A - } - Console.readkey (); the } - - Staticienumerable<int> getints (string[] strs) - { + foreach(varIteminchSTRs) - { + Console.WriteLine (item. GetType ()); A at //Here's an extension method. - yield returnitem. ToInt32 (); - } - } -}
Note The code in the Red section, and look at the results of the execution:
Description: Normal We do not add yield keyword, it is necessary to put the entire getints () method in the body of the Foreach loop after all the execution, and then make a judgment, now is not the same, you can debug by code to find: Yield will be executed to yield return
This line of code freezes and then transfers control to the outside, as long as the condition is met if (item>2) {break;}, so we can find his execution order by the result, which can be magnified, now only the number of data is small, if there are thousands of rows of objects
Data, then his performance is very obvious, find the conditions to meet the results can be returned;
Summary: The current code example yield keyword returns at once, this kind of usage, but understand the error; correctly understood as: the current block of code execution freezes, give control to the outside world, once the desired results are returned immediately, do not go down execution.
More information can be found in open source projects, such as EF and MVC, which are used extensively.
If interested, you are welcome to join Microsoft Combat Training Camp QQ group 203822816 for technical discussion exchange, which has the latest C # technology in the country, absolutely the latest Oh!!!
Yield keyword understanding in C #