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);
}

IEnumerable、IEnumerator接口(如何增加迭代器功能)的更多相关文章

  1. IEnumerable, IEnumerator接口

    IEnumerable接口 // Exposes the enumerator, which supports a simple iteration over a non-generic collec ...

  2. C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield

    IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...

  3. 迭代器学习之一:使用IEnumerable和IEnumerator接口

    写博客是检验我学习的成果之一以及自我总结的一种方式,以后会经常利用这种方式进行技术交流和自我总结,其中认识不深难免会有错误,但是一直懂得不懂就问,不懂就学的道理! 1.首先看一个简单的列子 , , , ...

  4. C# 通过IEnumberable接口和IEnumerator接口实现自定义集合类型foreach功能

    1.IEnumerator和IEnumerable的作用 其实IEnumerator和IEnumerable的作用很简单,就是让除数组和集合之外的类型也能支持foreach循环,至于foreach循环 ...

  5. C# 通过IEnumberable接口和IEnumerator接口实现泛型和非泛型自定义集合类型foreach功能

    IEnumerator和IEnumerable的作用 其实IEnumerator和IEnumerable的作用很简单,就是让除数组和集合之外的类型也能支持foreach循环,至于foreach循环,如 ...

  6. 细说 C# 中的 IEnumerable和IEnumerator接口

    我们先思考几个问题: 为什么在foreach中不能修改item的值? 要实现foreach需要满足什么条件? 为什么Linq to Object中要返回IEnumerable? 接下来,先开始我们的正 ...

  7. C#基础知识系列九(对IEnumerable和IEnumerator接口的糊涂认识)

    前言 IEnumerable.IEnumerator到现在为止对这两个接口还是不太理解,不理解但是自己总是想着试着要搞明白,毕竟自己用的少,所以在此先记录一下.以备自己日后可以来翻查,同时也希望园子里 ...

  8. C# IEnumerable 和 IEnumerator接口浅析

    温故而知新,可以为师矣,有空经常复习一下基础知识是有必要的,并且能加深理解和记忆. Foreach常用于循环访问集合,对实现IEnumerable的接口的容器进行遍历,IEnumerable和IEnu ...

  9. IEnumerable和IEnumerator接口

    我们先思考几个问题:1.为什么在foreach中不能修改item的值?(IEnumerator的Current为只读)2.要实现foreach需要满足什么条件?(实现IEnumerator接口来实现的 ...

随机推荐

  1. java web开发入门十(idea创建maven SSM项目)基于intellig idea

    一.搭建项目骨架 二.配置pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xm ...

  2. 【网络知识之六】UDP

    UDP(User Datagram Protocol)用户数据报协议,是一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务. 一.UDP报头UDP报头由4个部分组成,其中两个是可选的(粉红背 ...

  3. Web应急:搜索引擎劫持

    当你直接打开网址访问网站,是正常的,可是当你在搜索引擎结果页中打开网站时,会跳转到一些其他网站,比如博彩,虚假广告,淘宝搜索页面等.是的,你可能了遇到搜索引擎劫持. 现象描述 从搜索引擎来的流量自动跳 ...

  4. React setState没有及时更新

    1.封装 setFieldsValue 方法 /** * 更新state中的值 * data:{stateFieldName1:stateFieldvalue1...} */ setStateFiel ...

  5. Dapper学习(三)之其他用法

    这里说的其他用法,是指 Async,Buffered,Transaction,Stored Procedure. 1. 首先 dapper支持异步 ExecuteAsync, QueryAsync, ...

  6. SharpSocket类库功能介绍

    SharpSocket是高性能.轻量级.接口清晰.使用简单的C#语言编写的.NET通信类库.支持TCP收发文本和二进制数据,比如图片.音视频.文档等各类数据.SharpSocket封装了很多底层通信细 ...

  7. Delphi - Logs记录,函数实现MsgDsp

    Logs记录-函数实现MsgDsp 大多数时候,我们不太希望消息以交互的形式出现,这个时候我们可以在窗体上放置一个Memo,然后单独开一个线程进行监视,从而实现把消息实时的显示出来,便于开发者分析. ...

  8. vue自带开发环境,生产环境,自己搭建测试环境

    git 码云地址: https://gitee.com/qichangshui_admin/vueAddTest 参考地址: https://www.jianshu.com/p/bfcfe5fc253 ...

  9. How to use VideoToolbox to decompress H.264 video stream

    来源:http://stackoverflow.com/questions/29525000/how-to-use-videotoolbox-to-decompress-h-264-video-str ...

  10. java-log4j配置

    引入依赖: <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId ...