迭代器

在C# 2.0版本中,添加了一个“迭代器”的概念,它是方法、get访问器或运算符,使得开发人员能够在class或者struct中使用foreach语句进行迭代,而无需实现整个IEnumerable接口。在类或结构中,实现IEnumerator的GetEnumerator()方法,就可以遍历类中的数据结构。

    迭代器有着如下的特点:

  • 是一段可以返回相同类型的值的有序序列的代码;
  • 可用作方法、运算符或get访问器的代码体;
  • 使用yield return语句一次返回每一个元素;
  • 可以在类中实现多个迭代器,但必须具有唯一的名称;
  • 返回类型必须为IEnumerable或者IEnumerator。

yield 关键字用于指定返回的值。到达 yield return 语句时,会保存当前位置。下次调用迭代器时将从此位置重新开始执行。

在本示例中,DaysOfTheWeek 类是将一周中的各天作为字符串进行存储的简单集合类。foreach 循环每迭代一次,都返回集合中的下一个字符串。

IEnumerable接口例子:

public class DaysOfTheWeek : System.Collections.IEnumerable
{
    string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };

    public System.Collections.IEnumerator GetEnumerator()
    {
        for ( int i = 0; i < m_Days.Length; i++)
        {
            yield return m_Days[i];
        }
    }
}

class TestDaysOfTheWeek
{
    static void Main()
    {
        // Create an instance of the collection class
        DaysOfTheWeek week = new DaysOfTheWeek();

        // Iterate with foreach
        foreach ( string day in week)
        {
            System.Console.Write(day + " ");
        }
    }
}
IEnumerator接口例子:
下面就用一段实例代码来描述迭代器的用法。这段程序实现了一个类StudentList,里面存储有5个学生的字段,并且对于每个学生定义了一个属性。Main方法对这五个学生进行枚举并输出到控制台。先看一下传统的实现方法:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            StudentList myStudentList = new StudentList();

 

 

            Console.WriteLine(myStudentList.Student1);

            Console.WriteLine(myStudentList.Student2);

            Console.WriteLine(myStudentList.Student3);

            Console.WriteLine(myStudentList.Student4);

            Console.WriteLine(myStudentList.Student5);

 

            Console.ReadLine();

        }

 

        class StudentList

        {

            string student1 = "One";

            string student2 = "Two";

            string student3 = "Three";

            string student4 = "Four";

            string student5 = "Five";

 

            public string Student1

            {

                get

                {

                    return student1;

                }

                set

                {

                    student1 = value;

                }

            }

 

            public string Student2

            {

                get

                {

                    return student2;

                }

                set

                {

                    student2 = value;

                }

            }

 

            public string Student3

            {

                get

                {

                    return student3;

                }

                set

                {

                    student3 = value;

                }

            }

 

            public string Student4

            {

                get

                {

                    return student4;

                }

                set

                {

                    student4 = value;

                }

            }

 

            public string Student5

            {

                get

                {

                    return student5;

                }

                set

                {

                    student5 = value;

                }

            }

        }

    }

}

 

    可以看到在Main方法中这是很麻烦的做法,而且如果我们改动了StudentList中学生的个数,那么这段代码就不成立了。因此,在这里采用迭代器的方法,对程序加以改进。

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            StudentList myStudentList = new StudentList();

 

            // 使用foreach语句对迭代器进行遍历

            foreach (object student in myStudentList)

            {

                Console.WriteLine(student.ToString());

            }

 

            Console.ReadLine();

        }

 

        class StudentList

        {

            string student1 = "One";

            string student2 = "Two";

            string student3 = "Three";

            string student4 = "Four";

            string student5 = "Five";

 

            public string Student1

            {

                get

                {

                    return student1;

                }

                set

                {

                    student1 = value;

                }

            }

 

            public string Student2

            {

                get

                {

                    return student2;

                }

                set

                {

                    student2 = value;

                }

            }

 

            public string Student3

            {

                get

                {

                    return student3;

                }

                set

                {

                    student3 = value;

                }

            }

 

            public string Student4

            {

                get

                {

                    return student4;

                }

                set

                {

                    student4 = value;

                }

            }

 

            public string Student5

            {

                get

                {

                    return student5;

                }

                set

                {

                    student5 = value;

                }

            }

 

            /// <summary>

            /// StudentList类的迭代器

            /// </summary>

            public System.Collections.IEnumerator GetEnumerator()

            {

                // 通过循环来返回字段值

                for (int i = 0; i < 5; i++)

                {

                    // i进行判断,逐一返回值

                    switch (i)

                    {

                        case 0:

                            yield return student1;

                            break;

                        case 1:

                            yield return student2;

                            break;

                        case 2:

                            yield return student3;

                            break;

                        case 3:

                            yield return student4;

                            break;

                        case 4:

                            yield return student5;

                            break;                       

                    }

                }

            }

        }

    }

}

 

你可能感兴趣的:(迭代器)