C#中的IEnumerable和IEnumerator
1. 怎么理解C#中的 IEnumerable 和 IEnumerator
C# 中,可以通过 IEnumerable 接口,使得可以对特定的数据结构,使用foreach操作,在我理解,IEnumerator相当于C++中的iterator 迭代器。
假设,我们没有IEnumerable接口,要用IEnumerator迭代器实现foreach操作,我们会这么做:
//假设 迭代器为itor,类为Example
Example example;
IEnumerator itor = example.GetEnumerator();
while(itor.MoveNext()) //如果下一个对象不为空
{
Example exampleI = (Example)itor.Cureent ; 获取当前对象,将其传给exampleI
//Dosomething....
}
但是C#为我们设定了IEnumerable接口,使得我们可以将一个类继承这个接口,从而可以直接对其进行foreach操作。
比如C#中的容器List:
可以看到List支持各种类型的遍历foreach操作
同时C#的数组类型也是默认可以用foreach的
// Iterate over an array of items.
int[] myArrayOfInts = {10, 20, 30, 40};
foreach(int i in myArrayOfInts)
{
Console.WriteLine(i);
}
如果自己定义一个容器,不用IEnumerable接口,直接用foreach,会怎么样呢?
//定义一个车类型
public class Car
{
public string name;
public int price;
public Car(string _name, int _price)
{
name = _name;
price = _price;
}
}
//定义一个车库,用来存储车
public class Garage
{
private Car[] carArray = new Car[4];
// Fill with some Car objects upon startup.
public Garage()
{
carArray[0] = new Car("Rusty", 30);
carArray[1] = new Car("Clunker", 55);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
}
public static void Main()
{
Garage garage = new Garage();
foreach (Car c in garage)
{
Console.WriteLine(c.price);
}
}
发现报错了,不能使用foreach
提示的是,需要添加GetEnumerator的公共实例定义,也就是说,这个函数没有接口,来使用其迭代器。
所以需要给类添加可遍历的接口函数:
public IEnumerator GetEnumerator()
{
return carArray.GetEnumerator();
}
//IEnumerator IEnumerable.GetEnumerator() //这种写法也可以
//{
//return carArray.GetEnumerator();
//}
同时要把类改为:
public class Garage : IEnumerable
最后就可以输出了:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本