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