C#IEnumerable 接口


IEnumerable 接口
公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
命名空间:System.Collections

public class Person
    {
        public string firstName;
        public string lastName;
        public Person(string fName, string lName)
        {
            this.firstName = fName;
            this.lastName = lName;
        }
    }

    public class People : IEnumerable
    {
        private Person[] _person;
        public People(Person[] pArray)
        {
            _person = new Person[pArray.Length];
            for (int i = 0; i < pArray.Length; i++)
                _person[i] = pArray[i];
        }

        public PeopleEnum GetEnumerator()//返回PeopleEnum当前实例
        {
            return new PeopleEnum(_person);
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return (IEnumerator)GetEnumerator();
        }
    }

    public class PeopleEnum : IEnumerator
    {
        int position = -1;

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

        public Person Current
        {
            get
            {
                try { return _person[position]; }
                catch (IndexOutOfRangeException) { throw new InvalidOperationException(); }
            }
        }
        object IEnumerator.Current
        {
            get { return Current; }
        }

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

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

测试一下:

static void Main(string[] args)
        {
            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));

            Console.ReadKey();
        }

效果如下:


发布了334 篇原创文章 · 获赞 250 · 访问量 299万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览