C# 迭代器

方法一

可以通過申明一個迭代器的屬性實現迭代器
方法是
<訪問控制符> IEnumerable <T> 迭代器名稱
每次訪問迭代器,會從老地方進入迭代器函數,然後迭代器 yield 或終止,下次再從 yield 的下一行開始執行。
如果迭代器函數已經結束,不需要返回任何東西,foreach 會結束對其的訪問。



using System.Text;

namespace ConsoleApp1
{
    class Class2
    {
        static void Main()
        {
            foreach (string word in WordSequence("  @Fuck,you, leatherman!"))
            {
                Console.WriteLine(word);
            }
            Console.ReadKey();
        }

        public static IEnumerable<string> WordSequence(string str)
        {
            StringBuilder newWord = new StringBuilder(20);
            int status = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
                    status = 1;
                    newWord.Append(str[i]);
                }
                else if (status == 1)
                {
                    yield return newWord.ToString();
                    newWord.Clear();
                    status = 0;
                }
            }
            if (newWord.Length > 0)
            {
                yield return newWord.ToString();
            }
        } 
    } 
}

Outputs:

Fuck
you
leather
man

附:
1. C# 有和 Java 類似的 StringBuilder
2. string 的字符通過 str[i] 下標訪問。

方法2

實現IEnumerable接口,需要實現GetEmumerator方法

static void Main()  
{  
    DaysOfTheWeek days = new DaysOfTheWeek();  

    foreach (string day in days)  
    {  
        Console.Write(day + " ");  
    }  
    // Output: Sun Mon Tue Wed Thu Fri Sat  
    Console.ReadKey();  
}  

public class DaysOfTheWeek : IEnumerable  
{  
    private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };  

    public IEnumerator GetEnumerator()  
    {  
        for (int index = 0; index < days.Length; index++)  
        {  
            // Yield each day of the week.  
            yield return days[index];  
        }  
    }  
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章