C# Academy · 课时

yield break 与提前终止

根据条件停止迭代。

第 2 / 4 课13 个步骤

yield break 与提前终止 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 4 节课。

提前停止迭代器

有时,您希望迭代器在到达自然结尾之前停止生成值。yield break 语句会立即结束序列,就像迭代器中的 return 一样。

yield break 基础用法

yield break 会终止迭代器。不会再生成任何值,使用该迭代器的 foreach 循环也会结束。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> UpToFive()
    {
        for (int i = 1; i <= 100; i++)
        {
            if (i > 5) yield break;
            yield return i;
        }
    }

    public static void Main()
    {
        foreach (var n in UpToFive())
            Console.WriteLine(n);
    }
}

在条件满足时获取

一种常见模式是只要条件为真就生成元素,然后停止。使用 yield break 可以简洁地实现这一点。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> WhileSmall(IEnumerable<int> nums)
    {
        foreach (var n in nums)
        {
            if (n >= 10) yield break;
            yield return n;
        }
    }

    public static void Main()
    {
        foreach (var n in WhileSmall(new[] { 2, 4, 8, 12, 3 }))
            Console.WriteLine(n);
    }
}

使用 yield break 编写保护子句

您可以在迭代器开头使用 yield break 作为保护条件。如果输入为空或无效,就完全不返回任何元素。

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    static IEnumerable<string> Lines(string text)
    {
        if (string.IsNullOrEmpty(text)) yield break;
        foreach (var line in text.Split('\n'))
            yield return line;
    }

    public static void Main()
    {
        foreach (var l in Lines("a\nb\nc"))
            Console.WriteLine(l);
        Console.WriteLine("empty count: " + Lines("").Count());
    }
}

限制输出数量

使用计数器加上 yield break,即可限制迭代器生成的元素数量,即使源序列很长也不例外。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> Take(IEnumerable<int> source, int max)
    {
        int count = 0;
        foreach (var item in source)
        {
            if (count++ >= max) yield break;
            yield return item;
        }
    }

    public static void Main()
    {
        foreach (var n in Take(new[] { 1, 2, 3, 4, 5 }, 3))
            Console.WriteLine(n);
    }
}

调用方 break 与 yield break

序列有两种结束方式。调用方可以使用 break 停止获取值,或者迭代器可以使用 yield break 停止生成值。两者都会结束循环,但原因不同。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> Counting()
    {
        int i = 1;
        while (true) yield return i++;
    }

    public static void Main()
    {
        // Caller decides to stop with break
        foreach (var n in Counting())
        {
            if (n > 3) break;
            Console.WriteLine(n);
        }
    }
}

yield break 仅结束当前迭代器

yield break 只会退出它所在的迭代器方法,不会退出调用方中的外层循环。控制权会返回给正在枚举该序列的代码。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> Bounded(IEnumerable<int> nums, int limit)
    {
        foreach (var n in nums)
        {
            if (n > limit) yield break; // ends Bounded only
            yield return n;
        }
    }

    public static void Main()
    {
        var result = Bounded(new[] { 1, 2, 9, 3 }, 5);
        Console.WriteLine("iterator created, still running");
        foreach (var n in result) Console.WriteLine(n);
    }
}

yield break 后不再执行 yield return

一旦执行 yield break,迭代器就结束了。同一路径中位于它之后的任何代码都无法再生成值。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> Demo(bool stopEarly)
    {
        yield return 1;
        if (stopEarly) yield break;
        yield return 2;
        yield return 3;
    }

    public static void Main()
    {
        Console.WriteLine("stopEarly = true:");
        foreach (var n in Demo(true)) Console.WriteLine(n);
        Console.WriteLine("stopEarly = false:");
        foreach (var n in Demo(false)) Console.WriteLine(n);
    }
}

结合筛选与提前停止

您可以在同一个迭代器中同时进行筛选和终止:跳过某些值,生成其他值,并在出现哨兵值时彻底退出。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> UntilZero(IEnumerable<int> nums)
    {
        foreach (var n in nums)
        {
            if (n == 0) yield break;     // stop at sentinel
            if (n < 0) continue;         // skip negatives
            yield return n;
        }
    }

    public static void Main()
    {
        foreach (var n in UntilZero(new[] { 3, -1, 5, 0, 9 }))
            Console.WriteLine(n);
    }
}

提前结束迭代与最终执行代码块

如果您的迭代器包含 try/finally,当 yield break 结束序列时,finally 仍会执行。这可确保完成关闭资源等清理工作。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> WithCleanup()
    {
        try
        {
            yield return 1;
            yield break;
        }
        finally
        {
            Console.WriteLine("cleanup ran");
        }
    }

    public static void Main()
    {
        foreach (var n in WithCleanup())
            Console.WriteLine(n);
    }
}

亲自尝试

Combine 过滤与提前终止:生成正数,但一旦它们的运行 sum 超出预算,就完全停止。

using System;
using System.Collections.Generic;

public class Program
{
    static IEnumerable<int> WithinBudget(IEnumerable<int> nums, int budget)
    {
        int spent = 0;
        foreach (var n in nums)
        {
            if (n <= 0) continue;
            if (spent + n > budget) yield break;
            spent += n;
            yield return n;
        }
    }

    public static void Main()
    {
        foreach (var n in WithinBudget(new[] { 3, -2, 4, 5, 1 }, 10))
            Console.WriteLine(n);
    }
}

快速检查

回顾提前结束迭代的作用。

回顾

yield break 会提前结束迭代器。

  • 它的作用类似于迭代器中不返回值的 return。
  • 您可以将它用于只要满足条件就持续提取的逻辑、守卫条件和数量限制。
  • 它只会结束迭代器,不会结束调用方循环。
  • finally 代码块仍会执行,从而确保完成清理工作。
免费开始

用 AI 导师学习 C# — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
93
课程
346

常见问题解答

「yield break 与提前终止」课时是免费的吗?

是的 — 「yield break 与提前终止」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 4 节课。

「yield break 与提前终止」这节课中我会学到什么?

根据条件停止迭代。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「yield break 与提前终止」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 yield return 的迭代器方法
  2. yield break 与提前终止
  3. 惰性求值语义
  4. 自定义可枚举类型
← 返回 C# Academy