博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IEnumerable.GetEnumerator Method
阅读量:6289 次
发布时间:2019-06-22

本文共 2303 字,大约阅读时间需要 7 分钟。


The following code example demonstrates the implementation of the  interfaces for a custom collection. In this example, GetEnumerator is not explicitly called, but it is implemented to support the use of foreach (For Each in Visual Basic). This code example is part of a larger example for the  interface.

C#
 
using System;using System.Collections;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 = 0; 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 = -1;    public PeopleEnum(Person[] list)    {        _people = list;    }    public bool MoveNext()    {        position++;        return (position < _people.Length);    }    public void Reset()    {        position = -1;    }    object IEnumerator.Current    {        get        {            return Current;        }    }    public Person Current    {        get        {            try            {                return _people[position];            }            catch (IndexOutOfRangeException)            {                throw new InvalidOperationException();            }        }    }}class App{    static void Main()    {        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);    }}/* This code produces output similar to the following: * * John Smith * Jim Johnson * Sue Rabon * */

转载于:https://www.cnblogs.com/zhangchenliang/archive/2013/01/07/2848607.html

你可能感兴趣的文章
Flex&Bison手册
查看>>
solrCloud+tomcat+zookeeper集群配置
查看>>
/etc/fstab,/etc/mtab,和 /proc/mounts
查看>>
Apache kafka 简介
查看>>
socket通信Demo
查看>>
技术人员的焦虑
查看>>
js 判断整数
查看>>
mongodb $exists
查看>>
js实现页面跳转的几种方式
查看>>
sbt笔记一 hello-sbt
查看>>
常用链接
查看>>
pitfall override private method
查看>>
!important 和 * ----hack
查看>>
聊天界面图文混排
查看>>
控件的拖动
查看>>
svn eclipse unable to load default svn client的解决办法
查看>>
Android.mk 文件语法详解
查看>>
QT liunx 工具下载
查看>>
内核源码树
查看>>
Java 5 特性 Instrumentation 实践
查看>>