c#进阶-11.迭代器

迭代器(iterator)提供一种方法顺序访问一个聚合对象的元素,而不暴露内部的标识,是可以在容器上遍历访问的接口

凡是可以用foreach遍历的类都实现了迭代器

用法:

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 迭代器
{
    #region 标准迭代器的使用
    //接口:IEnumerable, IEnumerator
    //命名空间:using System.Collections;
    
    class Test : IEnumerable, IEnumerator
    {
        private int[] list;
        public int pos = -1;
        public Test()
        {
            list = new int[] { 1, 2, 3, 4, 5 };
        }
        #region IEnumerable
        public IEnumerator GetEnumerator()
        {
            Reset();
            return this;
        }
        #endregion

        #region IEnumerator
        public object Current
        {
            get
            {
                return list[pos];
            }
        }
        //获取下一光标
        public bool MoveNext()
        {
            pos++;
            return pos < list.Length;
        }
        //重置光标位置,一般写在GetEnumerator方法中
        public void Reset()
        {
            pos = -1;
        }
        #endregion      
    }
    #endregion
    #region 用yield return语法糖实现迭代器
    //主要作用将复杂代码简单化
    //实现接口IEnumerable
    class list2 : IEnumerable
    {
        private int[] list;
        public list2()
        {
            list = new int[] { 1, 2, 3, 4, 5 ,6};
        }
        public IEnumerator GetEnumerator()
        {
            for(int i=0;i<list.Length;i++)
            {
                //yield理解为暂时返回,保留当前状态
                //yield里面系统还是会调用MoveNext那些方法,我们不用写罢了,原理一样
                yield return list[i];
            }
        }
    }
    #endregion
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            //foreach的本质
            //1.先获取in后面这个对象的IEnumerable调用GetEnumerator(),不继承IEnumerable也可以
            //2.执行得到IEnumerator对象调用其MoveNext方法
            //3.只有MoveNext返回为true,就回去得到Current,然后复制给item
            
            foreach (int item in t)
            {
                Console.WriteLine(item);
            }
            list2 l2 = new list2();
            foreach (int item in l2)
            {
                Console.WriteLine(item);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值