IEnumerator 枚举使用

来源:互联网 发布:mac安装迅雷 编辑:程序博客网 时间:2024/05/21 14:49

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

namespace TestEffectEntry
{
    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];

            }

        }
        public IEnumerator GetEnumerator()
        {

            //return new PeopleEnum(_people);

            //return _people.GetEnumerator();


            for (int i = 0; i < _people.Length; i++)
            {

                yield return _people[i];
            }
        }
    }


    public class PeopleEnum : IEnumerator
    {

        public Person[] _people;

        int position = -1;

        public PeopleEnum(Person[] list)
        {
            _people = list;
        }

        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

        public void Reset()
        {
            position = -1;

        }

        public object Current
        {
            get
            {
                try
                {
                    return _people[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person[] peopleArray = new Person[3];
            peopleArray[0] = new Person("John", "Smith");
            peopleArray[1] = new Person("Jim", "Johnson");
            peopleArray[2] = new Person("Sue", "Rabon");

            People peopleList = new People(peopleArray);
           // foreach (Person p in peopleList)
            //    Console.WriteLine(p.firstName + " " + p.lastName);

            IEnumerator itor = peopleArray.GetEnumerator();
            while (itor.MoveNext())
            {
                Person p = itor.Current as Person;
                Console.WriteLine(p.firstName + " " + p.lastName);
            }
            Console.ReadKey();
        }
    }
}