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接口的元数据

在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
}
复制代码

编写测试方法

复制代码
View Code
      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属性

 

 

 

 

 

 

 

 

 

 

posted on   wolfram  阅读(798)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库

导航

< 2012年3月 >
26 27 28 29 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7
点击右上角即可分享
微信分享提示