C#中的迭代器

迭代器:迭代集合中的每一项,无需关心集合中的内容。

实现迭代器的传统方式是使用迭代器模式,迭代器模式的示意图如下:

 

http://images.cnblogs.com/cnblogs_com/cdts_change/Windows-Live-Writer/18Iterator-_D9C9/image_28.png

具体代码如下:

 

 

    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
    }
    class People:IEnumerable
    {
        public Person[] pvalue;
        public People(Person[] p)
        {
            pvalue = p;
        }
        public IEnumerator GetEnumerator()
        {
            return new PeopleEnumerator(this);
        }
        
    }

    class PeopleEnumerator:IEnumerator
    {
        Person[] pvalue;
        int position;
        public PeopleEnumerator(People p)
        {
            this.pvalue = p.pvalue;
            position = -1;
        }
        public bool MoveNext()
        {
            if (position >= -1 && position < pvalue.Length)
            {
                position++;
            }
            return position < pvalue.Length;
        }
        public object Current
        {
            get
            {
                if (position >= 0 && position < pvalue.Length)
                {
                    return pvalue[position];
                }
                else
                {
                    return null;
                }
            }
        }
        public void Reset()
        {
            position = -1;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            Person[] PClassOne = new Person[4];
            PClassOne[0] = new Person("夏利", 22);
            PClassOne[1] = new Person("大众", 25);
            PClassOne[2] = new Person("华为", 23);
            PClassOne[3] = new Person("中兴", 24);

            Console.WriteLine("传统的迭代器模式");
            People Ppeople = new People(PClassOne);
            IEnumerator PE = Ppeople.GetEnumerator();
            while (PE.MoveNext())
            {
                Person p = (Person)PE.Current;
                Console.WriteLine("我的名字叫{0},我的年龄为{1}", p.Name, p.Age);
            }

            Console.ReadKey();
        }
    }

输出为:

.net 可以使用yield 的方式简化迭代器的使用,将People改成如下的形式

    class People:IEnumerable
    {
        public Person[] pvalue;
        public People(Person[] p)
        {
            pvalue = p;
        }
        public IEnumerator GetEnumerator()
        {
            for (int i = 0; i < pvalue.Length; i++)
            {
                yield return pvalue[i];
            }
        }
        
    }

无需在手动写IEnumerator,即可行程一个有效的迭代器。

 

 

 

 

转载于:https://www.cnblogs.com/Celvin-Xu/p/3434285.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值