This article mainly introduces the yield return usage in C #, comparing the use of yield return with the process of not using yield return, to more visually analyze yield
The use of return, the need for friends can refer to the next.
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:
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
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:
static
void
Main(
string
[] args)
{
foreach
(var item
in
FilterWithoutYield())
{
Console.WriteLine(item);
}
Console.ReadKey();
}
Output Result: 3,4
Use Yeild return to implement
static
IEnumerable<
int
> FilterWithYield()
{
foreach
(
int
i
in
GetInitialData())
{
if
(i > 2)
{
yield
return
i;
}
}
yield
break
;
Console.WriteLine(
"这里的代码不执行"
);
}
Client calls:
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".
Analysis of yield return usage in C #