编程语言
首页 > 编程语言> > C#中的迭代器

C#中的迭代器

作者:互联网

原文链接:http://www.cnblogs.com/Celvin-Xu/p/3434285.html

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

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

 

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

标签:迭代,People,C#,pvalue,Person,position,public
来源: https://blog.csdn.net/weixin_30455067/article/details/97912290