实现自定义集合的 IEnumerable 和 IEnumerator 接口

实现自定义集合的 IEnumerable 和 IEnumerator 接口

namespace ConsoleApplication1
{
    //定义Person类
    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;
        }

        //向下推移索引,返回Bool类型值
        public bool MoveNext()
        {
            position++;
            return (position < _people.Length);
        }

        //重置默认索引位置,默认下标为0
        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 Program
    {
        static void Main(string[] args)
        {
            //实例化Person
            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);
        }
    }
}

 

posted @ 2021-05-17 15:26  码农阿亮  阅读(91)  评论(0编辑  收藏  举报