foreach原理学习
foreach能遍历哪些什么样的数据类型?
实现了IEnumerable(getEnumerator())、IEnumerable<T>的接口都可以使用foreach进行遍历。
那么为什么实现这两个接口就有了遍历的能力呢?查看这两个接口的元数据
IEnumerable接口中,就一个 GetEnumerator()方法
// 摘要: // 公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。 [ComVisible( true )] [Guid( "496B0ABE-CDEE-11d3-88E8-00902754C43A" )] public interface IEnumerable { // 摘要: // 返回一个循环访问集合的枚举数。 // // 返回结果: // 可用于循环访问集合的 System.Collections.IEnumerator 对象。 [DispId(-4)] IEnumerator GetEnumerator(); } |
GetEnumerator()方法返回一个 可用于循环访问集合的 System.Collections.IEnumerator 对象。
再通过查看IEnumerator接口的元数据
// 摘要: // 支持对非泛型集合的简单迭代。 [ComVisible( true )] [Guid( "496B0ABF-CDEE-11d3-88E8-00902754C43A" )] public interface IEnumerator { object Current { get ; } bool MoveNext(); void Reset(); } |
在IEnumerator接口中,定义了Current 属性和MoveNext()以及Reset()方法
可以看到Current 属性只有get属性,而没有set属性
Current属性是获取当前元素值,MoveNext()方法返回值是bool类型,其作用是查找下一个元素,如果找到,元素则为Current属性,且返回true,否则返回fase.
Reset()让当前返回到第一个元素。
大致了解完原理之后,就可以自己写一个能被foreach遍历的类

public class MyList<T> : IEnumerable, IEnumerator
{
T[] array;
int index = -1;
private MyList()
{
}
public MyList(int count)
{
array=new T[count];
}
public void Add(T item)
{
index++;
array[index] = item;
}
#region IEnumerator 成员
public object Current
{
get { return array[index]; }
}
public bool MoveNext()
{
bool result=false;
if (index < array.Length - 1)
{
index++;
result = true;
}
return result;
}
public void Reset()
{
index = -1;
}
#endregion
#region IEnumerable 成员
public IEnumerator GetEnumerator()
{
return this;
}
#endregion
}
编写测试方法

MyList<int> array = new MyList<int>(3);
array.Add(1);
array.Add(2);
array.Add(3);
array.Reset();
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("Done");
Console.Read();
程式运行结果
foreach时,为什么不能对迭代出来的元素赋值,因为IEnumerator接口中定义的Current 属性只有get属性,而没有set属性
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库