GetEnumerator();yield
GetEnumerator()方法的实质实现:
说明:只要一个集合点出GetEnumerator方法,就获得了迭代器属性,就可以用MoveNext和Current来实现foreach的效果,如上图。
在.NET中,迭代器模式被IEnumerator和IEnumerable及其对应的泛型接口所封装。如果一个类实现了IEnumerable接口,那么就能够被迭代;调用GetEnumerator方法将返回IEnumerator接口的实现,它就是迭代器本身。
所以一般能用foreach实现的,都可以让集合点出GetEnumerator( ),即得到迭代器,就可以用:
while(ooo.MoveNext())
{
var = ooo.Current;
}//其实foreach后台实现机制如此!
*****************************************************************************


两个方法效果一样
********************************************************************************
yield关键字用法:
yield一般和迭代器,return或者break关键字结合使用一起使用。
例如:
1 publicclass List 2 { 3 public static IEnumerable Power(int number(2), int exponent(8))//使用yield return 使得返回值是一个迭代器类型 4 { 5 int counter =0; 6 int result =1; 7 while (counter++< exponent) 8 { 9 result = result * number; 10 yield return result; 11 } 12 } 13 14 staticvoid Main() 15 { 16 foreach (int i in Power(2, 8)) 17 { 18 Console.Write("{0} ", i); 19 } 20 } 21 }
/*
输出: Output: 2 4 8 16 32 64 128 256 // */
了解枚举的机制后,就不得不讲道yield:
1 class Program 2 { 3 staticvoid Main(string[] args) 4 { 5 foreach (var item in Person.Run()) 6 { 7 Console.WriteLine(item); 8 } 9 } 10 } 11 class Person 12 { 13 public static IEnumerable<int> Run() 14 { 15 List<int> list = new List<int>(); 16 foreach (var item in list) 17 { 18 yieldreturn item; 19 } 20 } 21 }
//yield会给你生成一个枚举类,而这个枚举类和刚才List中的Enumerator枚举类又无比的一样
yield关键字用法:
yield一般和迭代器,return或者break关键字结合使用一起使用。
例如:
publicclass List
{
public static IEnumerable Power(int number(2), int exponent(8))//使用yield return 使得返回值是一个迭代器类型
{
int counter =0;
int result =1;
while (counter++< exponent)
{
result = result * number;
yield return result;
}
{
public static IEnumerable Power(int number(2), int exponent(8))//使用yield return 使得返回值是一个迭代器类型
{
int counter =0;
int result =1;
while (counter++< exponent)
{
result = result * number;
yield return result;
}
}
staticvoid Main()
{
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
}
/*
Output:
2 4 8 16 32 64 128 256 //
*/

作者:Chaunce
GitHub:https://github.com/liuyl1992
公众号请搜:架构师高级俱乐部 SmartLife_com

声明:原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能等盈利行为
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理