IEnumerable接口使用

要使用foreach语句对对象遍历,对象必须实现IEnumerable接口,下面是一个Demo。

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

namespace CsharpBase
{
    class EnumerableDemo
    {
        public static void Run()
        {
            Child[] childs = new Child[3]
            {
              new Child("zhang xiao","18"),
              new Child("zhang li","19"),
              new Child("zhang fei","20")
            };

            People person = new People(childs);

            foreach (Child c in person)
            {
                Console.WriteLine(c.Name + "," + c.Age);
            }
        }
    }

    public class Child
    {
        public string Name;
        public string Age;
        public Child(string name, string age)
        {
            Name = name;
            Age = age;
        }
    }

    public class People : IEnumerable
    {
        Child[] childs;
        public People(Child[] arr)
        {
            childs = arr;
        }

        #region IEnumerable 

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new PeopleEnum(childs);
        }

        #endregion
    }

    public class PeopleEnum : IEnumerator
    {
        Child[] lstChild;
        int position = -1;

        public PeopleEnum(Child[] childs)
        {
            lstChild = childs;
        }

        #region IEnumerator 
        object IEnumerator.Current
        {
            get
            {
                try
                {
                    return lstChild[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        bool IEnumerator.MoveNext()
        {
            position++;
            return position < lstChild.Length;
        }

        void IEnumerator.Reset()
        {
            position = -1;
        }
        #endregion
    }
}

 

结果:

你可能感兴趣的:(IEnumerable接口使用)