实现IEnumable以迭代对象示例

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace StaticTest
{
    class Person           //被迭代对象
    {
        public string fName;
        public string lName;
        public Person(string fName,string lName)
        {
            this.fName = fName;
            this.lName = lName;
        }
    }

    class People:IEnumerable      //迭代对象的容器
    {
        private Person[] _people;
        public People(Person[] person)
        {
            _people = new Person[person.Length];
            for (int i = 0; i < person.Length; i++)
            {
                _people[i]=person[i];
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return new PeopleEnum(_people);
        }
    }
    class PeopleEnum : IEnumerator //迭代器
    {
        int position = -1;
        public Person[] _person;
        public PeopleEnum(Person[] person)
        {
            _person = person;
        }
        public bool MoveNext()
        {
            position++;
            return (position < _person.Length);
        }
        public void Reset()
        {
            position = -1;
        }
        public object Current
        {
            get
            {
                try
                {
                    return _person[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }

        }
    } 
    class Program
    {
        static void Main(string[] args)
        {
            Person[] person = {
                              new Person("张","三"),new Person("李","四"),new Person("王","五")
                              };
            People peo = new People(person);
            foreach (Person pp in peo)
            {
                Console.WriteLine("fName:"+pp.fName+",lName:"+pp.lName);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/liancs/p/3879358.html