首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用 yield break 中断递归 IEnumerable<T> 循环?

在C#中,yield break用于在迭代器函数中提前终止IEnumerable<T>循环。以下是如何使用yield break来中断递归IEnumerable<T>循环的示例:

代码语言:csharp
复制
using System;
using System.Collections;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        var example = new Example();
        foreach (var item in example.RecursiveIEnumerable(0))
        {
            Console.WriteLine(item);
        }
    }

    public IEnumerable<int> RecursiveIEnumerable(int depth)
    {
        if (depth > 5)
        {
            yield break;
        }

        for (int i = 0; i< depth; i++)
        {
            yield return i;
        }

        foreach (var item in RecursiveIEnumerable(depth + 1))
        {
            yield return item;
        }
    }
}

在这个示例中,RecursiveIEnumerable方法是一个迭代器函数,它返回一个IEnumerable<int>。当depth大于5时,yield break用于提前终止循环。

在这个例子中,我们没有使用任何云计算品牌商,因为这是一个纯C#编程问题。如果您有其他与云计算相关的问题,请随时提问。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券