[C#]实现IEnumerable接口来使用foreach语句的一个实例

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

namespace IEnumeratorSample
{
    class Person : IEnumerable                         //派生自IEnumerable,同样定义一个Personl类
    {
        public string Name;
        public string Age;
        public Person(string name, string age)
        {
            Name = name;
            Age = age;
        }

        private Person[] per;
        public Person(Person[] array)//重载构造函数,迭代对象,用一个数组来存放Person的集合,在后面用foreach来访问,但是仍然要实现GetEnumerator()
        {
            per = new Person[array.Length];

            for (int i = 0; i < array.Length; i++)
            {
                per[i] = array[i];
            }
        }

        public IEnumerator GetEnumerator()//实现GetEnumerator()接口
        {
            return new PersonEnum(per);//在这里调用PersonEnum
        }
    }

    class PersonEnum : IEnumerator                    //实现foreach语句内部,并派生
    {
        public Person[] _per;
        int position = -1;

        public PersonEnum(Person[] list)
        {
            _per = list;
        }

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

        public void Reset()
        {
            position = -1;
        }

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

    class Program
    {
        static void Main(string[] args)
        {
            Person[] per = new Person[2]                //同样初始化并定义2个Person对象
            {
                new Person("guojing","21"),
                new Person("muqing","21"),
            };

            Person personlist = new Person(per);            //初始化对象集合
            foreach (Person p in personlist)                //使用foreach语句
                Console.WriteLine("Name is " + p.Name + " and Age is " + p.Age);
            Console.ReadKey();
        }
    }
}

原文地址:https://www.cnblogs.com/lihaozy/p/1868717.html