c# IEnumerable--扩展方法

本文介绍了IEnumerable接口和IEnumerator枚举器在.NET中的作用,以及yield关键字在实现迭代器时的工作原理,通过实例展示了如何使用Student类和StudentEnumerator来遍历数据。
摘要由CSDN通过智能技术生成
namespace Linq
{

    /// <summary>
    /// IEnumerable可枚举类---可迭代类型
    /// IEnumerator枚举器
    /// 
    /// 只要实现了IEnumerable接口,就可以对他进行遍历
    /// yield关键词 他做了什么工作?他是一个迭代器,它相当于实现了IEnumerator枚举器
    /// </summary>
    class IEnumerableShow
    {
        public void Show()
        {
            int[] array = { 1, 2, 3, 4, 5, 6 };
            int i = 1;
            string str = "ANT编程";
            Student student = new Student { ID = 1 };
            foreach (var item in student)
            {
                Console.WriteLine(item);
            }

        }
    }

    class Student:IEnumerable
    {
        public int ID { get; set; }

        public IEnumerator GetEnumerator()
        {
            yield实现了IEnumerator接口
            //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
    {
        private 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;
        }
    }
}

如若不理解,思考list集合的遍历;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值