The
1.yield keyword is used to traverse loops, and yield return is used to return Ienumerable<t>,yield break for terminating loop traversal
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); //这里的add就把结果都给了result,返回一个List<int>类型的result对象,所以这里返回的结果result是List<int>类型,会转化为IEnumerable<int>类型
}
}
return result;
}
use yeild return to implement
static IEnumerable<int> FilterWithYield()
{
foreach (int i in GetInitialData())
{
if (i > 2)
{
yield return i;
}
}
yield break;
Console.WriteLine("这里的代码不执行");
}
The code for the client call is the same
static void Main(string[] args)
{
foreach (var item in FilterWithYield())
{
Console.WriteLine(item);
}
Console.ReadKey();
}
using this code to test a LINQ expression, the result is that the class of the method is not a ienumerable<t> type, only the return value of the method is Ienumerable<t>, so only the return value of the method can be used with LINQSo there are two conditions for using LINQ: 1. For classes, this class inherits Ienumerable<t>, and it is necessary to implement IEnumerator Getnumerator method 2. For methods, this method returns ienumerable<t Types of > interfacesAlthough 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".
Source: >
implementing the code for a IEnumerable interface
public class Stack : IEnumerable
{
int [] items = { 1 2 3 4 5 6 7 8 9 };
public IEnumerator GetEnumerator()
{
for (int i = 0; i < items.Length; i++)
{
yield return items[i]; // return返回的是IEnumerator集合对象,也就是说类中本身就有了一个
//IEnumerator对象,Foreach遍历的时候,也遍历的是这个IEnumerator对象,所以直接写foreach(var i in ss)就可以了,底层帮助完成其他代码
}
}
}
From for notes (Wiz)
Yield return usage in C #