IEnumerable、IEnumerator接口(如何增加迭代器功能)
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接口(如何增加迭代器功能)的更多相关文章
- IEnumerable, IEnumerator接口
IEnumerable接口 // Exposes the enumerator, which supports a simple iteration over a non-generic collec ...
- C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield
IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...
- 迭代器学习之一:使用IEnumerable和IEnumerator接口
写博客是检验我学习的成果之一以及自我总结的一种方式,以后会经常利用这种方式进行技术交流和自我总结,其中认识不深难免会有错误,但是一直懂得不懂就问,不懂就学的道理! 1.首先看一个简单的列子 , , , ...
- C# 通过IEnumberable接口和IEnumerator接口实现自定义集合类型foreach功能
1.IEnumerator和IEnumerable的作用 其实IEnumerator和IEnumerable的作用很简单,就是让除数组和集合之外的类型也能支持foreach循环,至于foreach循环 ...
- C# 通过IEnumberable接口和IEnumerator接口实现泛型和非泛型自定义集合类型foreach功能
IEnumerator和IEnumerable的作用 其实IEnumerator和IEnumerable的作用很简单,就是让除数组和集合之外的类型也能支持foreach循环,至于foreach循环,如 ...
- 细说 C# 中的 IEnumerable和IEnumerator接口
我们先思考几个问题: 为什么在foreach中不能修改item的值? 要实现foreach需要满足什么条件? 为什么Linq to Object中要返回IEnumerable? 接下来,先开始我们的正 ...
- C#基础知识系列九(对IEnumerable和IEnumerator接口的糊涂认识)
前言 IEnumerable.IEnumerator到现在为止对这两个接口还是不太理解,不理解但是自己总是想着试着要搞明白,毕竟自己用的少,所以在此先记录一下.以备自己日后可以来翻查,同时也希望园子里 ...
- C# IEnumerable 和 IEnumerator接口浅析
温故而知新,可以为师矣,有空经常复习一下基础知识是有必要的,并且能加深理解和记忆. Foreach常用于循环访问集合,对实现IEnumerable的接口的容器进行遍历,IEnumerable和IEnu ...
- IEnumerable和IEnumerator接口
我们先思考几个问题:1.为什么在foreach中不能修改item的值?(IEnumerator的Current为只读)2.要实现foreach需要满足什么条件?(实现IEnumerator接口来实现的 ...
随机推荐
- ORACLE--报错,ORA-38770
一,问题描述 背景说明,Dg备库需要恢复到三天前,但是期间没有开闪回,临时开始,出现了这个错误.原因分析: To enable Flashback Database, you configure a ...
- Elasticsearch由浅入深(二)ES基础分布式架构、横向扩容、容错机制
Elasticsearch的基础分布式架构 Elasticsearch对复杂分布式机制的透明隐藏特性 Elasticsearch是一套分布式系统,分布式是为了应对大数据量. Elasticsearch ...
- [翻译 EF Core in Action 2.4] 加载相关数据
Entity Framework Core in Action Entityframework Core in action是 Jon P smith 所著的关于Entityframework Cor ...
- Sql server锁
SQL Server锁粒度 1.锁粒度是被封锁目标的大小,封锁粒度小则并发性高,但开销大,封锁粒度大则并发性低但开销小 2.SQL Server支持的锁粒度可以分为为行.页.键.键范围.索引.表或数据 ...
- django实战(四)--修改数据
这节我们实现修改数据的功能,惯例,还是先上代码: urls.py urlpatterns=[ path('curd/edit/',views.curd_edit,name='curdedit'), p ...
- mac os 使用 from scipy.misc import imread ImportError: cannot import name 'imread'
mac os 使用 from scipy.misc import imread ImportError: cannot import name 'imread' 问题1: 我原先安装了 pillow ...
- 释放mac磁盘空间
转发自:https://www.jianshu.com/p/722093bc3dea Mac清理磁盘空间主要讲述在Mac上工作清理磁盘空间的小技巧,本节主要讲述作为一名使用Mac开发的iOS工程师,需 ...
- 记一次错误排查,主要问题是跨平台文件中换行符(CRLF, LF)和垃圾字符( Caret Notation)
笔者测试SPEC14的workload的时候,需要自定义workload,又需要在Windows和Linux平台上都要测试,所以就遇到了这么个问题:测试工具报错,但是报出来的错误信息又跟错误对不上. ...
- C# 分解文件路径目录
利用正则表达式分解文件目录 [^\\].*?[\\$]|[^\\].*?\.\w+|\w+ 测试字符串:C:\Users\wppcn\Desktop\中文长字符第一次测试\新建文件夹1\新建文件夹2\ ...
- 用vscode开发vue应用
阅读 3237 收藏 205 2019-05-02 原文链接:segmentfault.com 云服务器 1 核 2G , 9元/月 ,买十送二,99/年!!!快来上车!developer.huawe ...