在C#中,yield break
用于在迭代器函数中提前终止IEnumerable<T>
循环。以下是如何使用yield break
来中断递归IEnumerable<T>
循环的示例:
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#编程问题。如果您有其他与云计算相关的问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云