迭代器是 C#
迭代器概述
迭代器是可以返回相同類型的值的有序序列的一段代碼
迭代器可用作方法
迭代器代碼使用 yield return 語句依次返回每個元素
可以在類中實現多個迭代器
迭代器的返回類型必須為 IEnumerable
yield 關鍵字用於指定返回的值
迭代器對集合類特別有用
廢話不說了
public class DaysOfTheWeek : System
{
string[] m_Days = {
public System
{
for (int 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
}
}
}
運行結果為Sun Mon Tue Wed Thr Fri Sat
再舉個列子
using System;
using System
using System
namespace Test
{
public class Year : System
{
string[] season = {
public System
{
for (int i =
{
yield return season[i];
}
}
}
class Program
{
static void Main(string[] args)
{
Year y = new Year();
// 使用迭代器
foreach (string s in y)
{
System
}
Console
}
}
}
通過上面簡單的介紹希望你對迭代器有個簡單的認識
From:http://tw.wingwit.com/Article/program/net/201311/12348.html