下面的代码示例演示如何实现自定义集合的 IEnumerable 和 IEnumerator 接口:

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
} public string firstName;
public string lastName;
} public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length]; for (int i = ; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
} IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
} public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
} public class PeopleEnum : IEnumerator
{
public Person[] _people; // Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -; public PeopleEnum(Person[] list)
{
_people = list;
} public bool MoveNext()
{
position++;
return (position < _people.Length);
} public void Reset()
{
position = -;
} object IEnumerator.Current
{
get
{
return Current;
}
} public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
} class Program
{
static void Main(string[] args)
{
Person[] peopleArray = new Person[]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
}; People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
}

可枚举类型 → 实现IEnumerable接口,可以不需要直接实现这个接口,但必须有个GetEnumerator方法,返回值类型必须为IEnumerator类型,也就是第四点最后一段代码中接口注释的那种写法!

枚举数 → 实现IEnumerator接口,实现全部方法,首先是调用GetEnumerator返回一个类型为IEnumerator的枚举数,然后编译器会隐式的调用实现IEnumerator类中的方法和属性!

总结:所以实现foreach遍历,必须达到上面的两种条件才能进行遍历对象,他们可以写在一起也可以分开,最好是分开,进行职责分离,一个类干一件事总归是好事!也满足面向对象的单一指责设计原则。

最新文章

  1. .NET Core系列 :3 、使用多个项目
  2. Android自定义Dialog(美化界面)
  3. java 深入技术一
  4. 装饰模式(Decorate Pattern)
  5. 抢小米软件html版(简单有效)
  6. How to export a template in Visual Studio?
  7. 初接触eclipse和前后端调试问题 待续
  8. c++学习——类成员的访问权限
  9. MySQL备份与复制
  10. 《Pro Git》学习笔记
  11. jq总结
  12. poj 2299 逆序数
  13. Extjs 4.0 Window
  14. windows 7蓝屏解决办法
  15. 剑指offer:顺时针打印矩阵
  16. js中创建对象的5种方法
  17. keras用vgg16做图像分类
  18. 微信小程序-bug-调用wx.login()无响应的原因和解决方案
  19. 浅谈 Java JPDA
  20. 《Go语言实战》摘录:6.5 并发 - 通道

热门文章

  1. SpringMVC笔记2
  2. Github-Q&amp;A 常见错误排查(持续更新)
  3. Linux 进程间通信(管道、共享内存、消息队列、信号量)
  4. 『Go基础』第6节 注释
  5. 【LEETCODE】40、1051. Height Checker
  6. mysql删除字符串的前后的空格
  7. tkinter学习笔记_03
  8. JDBC第一个案例
  9. 【洛谷 P4254】 [JSOI2008]Blue Mary开公司(李超线段树)
  10. 北航OO课程完结总结