循环后是否需要调用“ yield break”?

Ade*_*rov 2 c#

在我的代码中,我有一个像这样的方法

public static IEnumerable<int> GetDiff(int start, int end)
{
    while (start < end)
    {
        yield return start;
            start++;
    }
    yield break; // do we need to call it explicitly?
}
Run Code Online (Sandbox Code Playgroud)

因此,我感兴趣的测试用例是GetDiff(1, 5)GetDiff(5, 1)。虽然很明显在第一种情况下会发生什么,但是还不清楚第二种情况下如何在没有yield break;after循环的情况下完成它

Sta*_*sky 7

不,这不是必需的。它将起作用:

public static IEnumerable<int> GetDiff(int start, int end)
{
    while (start < end)
    {
        yield return start;
        start++;
    }
    // yield break; - It is not necessary. It is like `return` which does not return a value.
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该函数的执行将仅通过退出而结束。

但是您可以这样写:

public static IEnumerable<int> GetDiff(int start, int end)
{
    while (true)
    {
        if (start >= end)
            yield break;
        yield return start;
        start++;
    }
    Console.WriteLine("Finish"); // note that this line will not be executed
}
Run Code Online (Sandbox Code Playgroud)