This example describes the yield return usage in C #, and compares the use of yield return with no yield return for a better understanding of the reader. Specific as follows:
The yield keyword is used to iterate through the loop, and yield return is used to return the Ienumerable<t>,yield break used to terminate the loop traversal.
There is a collection of such an int type:
?
1234 |
static List< int > GetInitialData() { return new List< int >(){1,2,3,4}; } |
You need to print out all elements with values greater than 2.
Implementations that do not use yield return
?
123456789101112 |
static IEnumerable<
int
> FilterWithoutYield()
{
List<
int
> result =
new List<
int
>();
foreach (
int i
in GetInitialData())
{
if (i > 2)
{
result.Add(i);
}
}
return result;
}
|
Client calls:
?
12345678 |
static void Main( string [] args) { foreach (var item in FilterWithoutYield()) { Console.WriteLine(item); } Console.ReadKey(); } |
Output Result: 3,4
Use Yeild return to implement
?
123456789101112 |
static IEnumerable<
int
> FilterWithYield()
{
foreach (
int i
in GetInitialData())
{
if (i > 2)
{
yield return i;
}
}
yield break
;
Console.WriteLine(
"这里的代码不执行"
);
}
|
Client calls:
?
12345678 |
static void Main( string [] args) { foreach (var item in FilterWithYield()) { Console.WriteLine(item); } Console.ReadKey(); } |
Output Result: 3,4
Summarize:
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".
I hope this article is helpful to everyone's C # programming.
Yield return usage analysis in C # (reprinted from shichen2014)