C# IEnumerator枚举器

1、对象只要一个类型实现了IEnumerable接口就能遍历
2、IEnumerator是枚举器,一个接口类,实现MoveNext->Current->Reset
3、yield关键字是一个迭代器,相当于实现了IEnumerator枚举器
4、IEnumerable是可枚举类型,IEnumerator是枚举器

public class IEnumerableShow {
        public void Show() {
            int[] array = { 1, 2, 3, 4, 5 };
            Student student = new Student { Id = 1 };
            foreach (var item in array) {
                Console.WriteLine();
            }
        }
    }

    class Student:IEnumerable { 
        public int Id { get; set; }
        public IEnumerator GetEnumerator() { //返回一个枚举器
            //yield return "Ant编程1";
            //yield return "Ant编程2";
            //yield return "Ant编程3";
            string[] student = { "Ant编程1", "Ant编程2", "Ant编程3" };
            return new StudentEnumerator(student);
        }
    }

    internal class StudentEnumerator : IEnumerator
    {
        string[] _student;
        int _position = -1;
        public StudentEnumerator(string[] student) {
            this._student = student;
        }

        public object Current {
            get {
                if (_position == -1) {
                    throw new InvalidOperationException();
                }
                if (_position>=_student.Length) {
                    throw new InvalidOperationException();
                }
                return _student[_position];
            }
        }

        public bool MoveNext()
        {
            if (_position<_student.Length-1) {
                _position++;
                return true;
            }
            else {
                return false;
            }
        }

        public void Reset()
        {
            _position = -1;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值