排名
7
文章
192
粉丝
15
评论
16
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

话不多说,先看看代码
public static IEnumerable<int> enumerableFuc()
{
yield return 1;
yield return 2;
yield return 3;
}
foreach (var item in enumerableFuc())
{
Console.WriteLine(item);
}
输出结果
通过yield return实现了类似用foreach遍历数组的功能,说明yield return也是用来实现迭代器的功能
现在我们把enumerableFuc方法换一下
public static IEnumerable<int> enumerableFuc()
{
yield return 1;
yield return 2;
yield break;
yield return 3;
}
foreach (var item in enumerableFuc())
{
Console.WriteLine(item);
}
现在在输出结果
能看到只输出了1,2
说明这个迭代器被yield break停掉了,所以yield break是用来终止迭代的。
注意
只能使用在返回类型必须为 IEnumerable、IEnumerable
评价