1. 樣本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace NetTest
{
public class TestIteration
{
public void Test()
{
SevenColor colorIteration = new SevenColor();
foreach (string p in colorIteration)
{
Console.Out.WriteLine(p);
}
Console.Out.WriteLine("-------------Desc-------------------");
foreach (string c in colorIteration.DescColorIteration(1, 5))
{
Console.Out.WriteLine(c);
}
Console.Out.WriteLine("--------------multi yield---------");
foreach (string c in colorIteration.GetMutipleYied())
{
Console.Out.WriteLine(c);
}
}
}
public class SevenColor : IEnumerable
{
string[] mColor={"red","orange","yellow","green","cyan","blue","purple"};
#region IEnumerable Members
/*
迭代器代碼使用 yield return 語句依次返回每個元素。yield break 將終止迭代。
可以在類中實現多個迭代器。每個迭代器都必須像任何類成員一樣有唯一的名稱,
並且可以在 foreach 語句中被用戶端代碼調用,如下所示:foreach(int x in SampleClass.Iterator2){}
*/
public IEnumerator GetEnumerator()
{
for (int i = 0; i < mColor.Length; i++)
{
yield return mColor[i];
}
}
#endregion
//注意,這裡返回的是IEnumerable
public System.Collections.IEnumerable DescColorIteration(int start, int end)
{
for (int i = 0; i <=end; i++)
{
yield return mColor[end-i];
}
}
//在 foreach 迴圈的每次後續迭代(或對 IEnumerator.MoveNext 的直接調用)中,
//下一個迭代器代碼體將從前一個 yield 語句之後開始,並繼續下一個語句直至到達迭代器體的結尾或遇到 yield break 語句
public IEnumerable GetMutipleYied()
{
yield return "hello";
yield return "I am";
yield return "Jack";
yield return "wang";
}
}
}
2. 輸出