<pre name="code" class="csharp">using System;
using System.Collections;
public class List
{
public bool onOff = false;
public static IEnumerable ForExample()
{
yield return "1"; // 第一次调用时执行
yield return "2"; // 第二次调用时执行
if (onOff) // 第三次调用时执行
{
// 执行 yield break 之后不再执行下面语句
yield break;
}
// 否则,onOff为 false
yield return "3"; // 第四次调用时执行
yield return "4"; // 第五次调用时执行
}
static void Main()
{
foreach (string s in ForExample())
Console.WriteLine(s);
Console.ReadKey();
}
}
using System.Collections;
public class List
{
public bool onOff = false;
public static IEnumerable ForExample()
{
yield return "1"; // 第一次调用时执行
yield return "2"; // 第二次调用时执行
if (onOff) // 第三次调用时执行
{
// 执行 yield break 之后不再执行下面语句
yield break;
}
// 否则,onOff为 false
yield return "3"; // 第四次调用时执行
yield return "4"; // 第五次调用时执行
}
static void Main()
{
foreach (string s in ForExample())
Console.WriteLine(s);
Console.ReadKey();
}
}
本文通过一个具体的C#代码示例展示了如何使用迭代器(yield)来创建灵活且节省内存的枚举器。该枚举器可以按需生成序列中的元素,尤其在条件控制下能够有效地管理执行流程。
723

被折叠的 条评论
为什么被折叠?



