今天项目中用到了 yield return ,主要是为了实现 延迟迭代的需求,所以就写了这个小的 Demo,希望对你有帮助!
代码如下:
代码如下:
using System;
using System.Collections.Generic;
namespace ConAppYield
{
class Program
{
static void Main(string[] args)
{
// Yield 的好处是 延迟遍历,只有在遍历具体的数据时才去执行对应的代码,Linq 中大量的扩展方法用到了,比如:select 等等
Console.WriteLine("==偶数年龄如下:==");
IEnumerable<int> query = Students.GetEvenNumbers();
foreach (var item in query)
{
Console.WriteLine(item);
}
Console.WriteLine("==下面用 do while 模拟 C# 中的 foreach 循环,说到底,foreach 循环只是 C# 的语法糖而已! ==");
Console.WriteLine("==同时,foreach 循环也是一种设计模式,叫 迭代模式==");
IEnumerator<int> newQuery = query.GetEnumerator();
int i = 0;
while(newQuery.MoveNext())
{
i++;
Console.WriteLine("集合中的第 "+ i +" 个数:" + newQuery.Current);
}
Console.ReadKey();
}
}
class Students
{
private static readonly int[] ages = new int[] { 1,2,3,4,5,6,7,8,9,10 };
public static IEnumerable<int> GetEvenNumbers()
{
int agesLength = ages.Length;
for (int i = 0; i < agesLength; i++)
{
if (ages[i] % 2 == 0)
{
yield return ages[i];
}
else
{
//yield break; //yield break 可以终止循环,即:只要碰到的数不是偶数,则立即终止循环
}
}
/* 下面的写法错误:无法在包含 catch 子句的 Try 块体中生成值 */
/*
try
{
foreach (var item in ages)
{
if (item % 2 == 0)
{
yield return item;
}
}
}
catch (Exception)
{
throw;
}*/
}
}
}
谢谢浏览!