IEnumerable、IEnumerator接口封装了迭代器功能,有了它,我们不需要将内部集合暴露出去,外界只需要访问我的迭代器接口方法即可遍历数据。

在C#中,使用foreach语句来遍历集合。foreach语句是微软提供的语法糖,使用它可以简化C#内置迭代器的使用复杂性。编译foreach语句,会生成调用GetEnumerator和MoveNext方法以及Current属性的代码。

有两种实现迭代器的方式,一是自己继承IEnumerable接口,比较复杂;二是使用yield,简化操作,下面会有案例。

反编译foreach,生成类似下面这段代码:

 IEnumerator<Student> studentEnumerator = studentList.GetEnumerator();
while (studentEnumerator.MoveNext())
{
var currentStudent = studentEnumerator.Current as Student;
Console.WriteLine("Id = {0}, Name = {1}, Age = {2}", currentStudent.Id, currentStudent.Name, currentStudent.Age);
}

案例1:给自己的类增加迭代器功能

     public class StudentSet : IEnumerable
{
private Student[] students;
public StudentSet(Student[] inputStudents)
{
students = new Student[inputStudents.Length];
for (int i = ; i < inputStudents.Length; i++)
{
students[i] = inputStudents[i];
}
} IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
} public StudentEnumerator GetEnumerator()
{
return new StudentEnumerator(students);
}
} public class StudentEnumerator : IEnumerator
{
public Student[] students;
int position = -;
public StudentEnumerator(Student[] students)
{
this.students = students;
} public bool MoveNext()
{
position++;
return (position < students.Length);
} public void Reset()
{
position = -;
} object IEnumerator.Current
{
get
{
return Current;
}
} public Student Current
{
get
{
try
{
return students[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}

案例2:使用yield实现迭代器功能

    public class MyCollection
{
private int[] list = new int[] { , , , }; public IEnumerator<int> GetEnumerator()
{
for (int i = ; i < list.Length; i++)
{
yield return list[i];
}
}
}
 MyCollection col = new MyCollection();
foreach (var item in col)
{
Console.WriteLine(item);
}

最新文章

  1. Hawk 5.1 数据导入和导出
  2. 还来一篇说下json_value 以及 json_query 的应用 (3)
  3. freeCAD定制界面
  4. 基于吉日嘎底层架构的通用权限管理Web端UI更新:参考DTcms后台界面
  5. 在iframe中获取本iframe DOM引用
  6. ggplot2.multiplot:将多个图形使用GGPLOT2在同一页上
  7. Python学习总结18:函数 参数篇
  8. Python笔记6(异常)-20160924
  9. jquery控制audio的播放与暂停
  10. MongoDB的安装和使用指南
  11. CanalSharp-mysql数据库binlog的增量订阅&amp;消费组件Canal的.NET客户端
  12. Servlet版本冲突引起的Error
  13. Mac 启用NTFS
  14. jQuery的ID选择器失效问题
  15. SpringBoot的json序列化及时间序列化处理
  16. noip第13课作业
  17. linux虚拟机与winodows共享文件夹----linux安装VMware tools
  18. 转:Java中字符串split() 的使用方法.
  19. 远程连接mysql数据库提示:ERROR 1130的解决办法
  20. 【Codeforces】Codeforces Round #491 (Div. 2) (Contest 991)

热门文章

  1. vue系列--vue是如何实现绑定事件
  2. Azure DevOps Server (TFS) 代码库Repo管理培训
  3. 运行带参数的python脚本
  4. 19条常用的MySQL优化方法(转)
  5. UVA 10924 Prime Words 题解
  6. WPF DataGrid 使用CellTemplateSelector 时SelectTemplate方法Item参数为NULL
  7. uni-app如何解决在for循环里调用异步请求获取数据顺序混乱问题?
  8. (一)RFB协议概述
  9. 洛谷P1523 旅行商简化版(DP)
  10. 搜索引擎elasticsearch监控利器cat命令