0x01 - c#自问自答 - yield
1. yield 是什么?
yield 关键字是实现 IEnumerable
接口的语法糖
.
class czList : IEnumerable
{
private int[] array = new int[10] { 1,2,3,4,5,6,7,8,9,10};
public IEnumerator GetEnumerator()
{
yield return "Hello";
yield return "World";
for (int i = 0; i < 10; i++)
{
if (i < 5)
yield return array[i];
else
yield break;
// break 会切断后续的return
}
}
}
var data = new czList();
foreach (var item in data)
{
Console.WriteLine(item);//这里的item识别出来是object
//yield会按yield return 顺序,依次返回相应的object
}
//out:Hello
//out:World
//out:1
//out:2
//out:3
//out:4
//out:5