C#IEnumerable 接口
来源:互联网 发布:魔法特效软件新白良子 编辑:程序博客网 时间:2024/05/13 23:28
IEnumerable 接口
公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
命名空间:System.Collections
public class Person { public string firstName; public string lastName; public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } } public class People : IEnumerable { private Person[] _person; public People(Person[] pArray) { _person = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) _person[i] = pArray[i]; } public PeopleEnum GetEnumerator()//返回PeopleEnum当前实例 { return new PeopleEnum(_person); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } } public class PeopleEnum : IEnumerator { int position = -1; public Person[] _person; public PeopleEnum(Person[] list) { _person = list; } public Person Current { get { try { return _person[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { position++; return (position < _person.Length); } public void Reset() { position = -1; } }
测试一下:
static void Main(string[] args) { Person[] peopleArray = new Person[3] { 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)); Console.ReadKey(); }
效果如下:
- C#IEnumerable 接口
- IEnumerable接口
- IEnumerable接口
- IEnumerable 接口
- IEnumerable和IEnumerable<T>接口
- IEnumerable和IEnumerable<T>接口
- IEnumerable和IEnumerable<T>接口
- IEnumerable和IEnumerable T接口
- IEnumerable和IEnumerable<T>接口
- C#: IEnumerable
- IEnumerable 和 IEnumerator 接口
- IEnumerable 和 IEnumerator 接口
- IEnumerable 和 IEnumerator 接口
- IEnumerable和IEnumerator接口
- IEnumerable接口主要成员
- IEnumerable接口与IEnumerator
- IEnumerable接口和迭代器
- IEnumerable接口使用
- 集群节点列表编辑程序
- 关于浮动元素排版问题
- piece of code(4)
- 分布式单词发音抓取机器人
- 编译Mysql configure: error: No curses/termcap library found 的错误解决方法
- C#IEnumerable 接口
- 查看硬件信息几种方法
- ubuntu11.04下配置中文输入法
- ubuntu11.04下安装QQ2012
- Linux 下从命令行打开pdf文件和html文件的命令
- Ubuntu下使用GAE翻墙
- 让进程的运行不受终端影响的几个方法
- Linux 下从命令行打开pdf文件和html文件的命令
- Linux配置支持C/C++项目的eclipse和支持java项目的eclipse