在C# 2.0版本中,添加了一個“迭代器”的概念,它是方法、get訪問器或運算符,使得開發人員能夠在class或者struct中使用foreach語句進行迭代,而無需實現整個IEnumerable接口。在類或結構中,實現IEnumerator的GetEnumerator()方法,就可以遍歷類中的數據結構。
迭代器有著如下的特點:
下面就用一段實例代碼來描述迭代器的用法。這段程序實現了一個類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";
{
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;
}
}
}
}
}
}