Skip to content
Rain Hu's Workspace
Go back

[C#] IEnumerable & IEnumerator 迭代器

Rain Hu

1. 簡介

public static IEnumerable<int> GetFibonacciSeries(int end)
{
    int cnt = 0;
    int prev = 0;
    int curr = 1;
    while (true)
    {
        if (cnt == end) yield break;
        cnt++;
        int tmp = curr + prev;
        yield return curr;
        prev = curr;   
        curr = tmp;
    }
}
public static void Main(string[] args)
{
    
    foreach(int val in GetFibonacciSeries(10))
    {
        Console.WriteLine(val);
    }
}    

2. 延遲執行

public static List<int> GetFibonacciSeriesList(int end)
{
    int cnt = 0;
    int prev = 0;
    int curr = 1;
    List<int> res = new List<int>();
    while (true)
    {
        if (cnt == end) break;
        cnt++;
        int tmp = curr + prev;
        res.Add(curr);
        prev = curr;
        curr = tmp;
    }
    return res;
}
public static void Main(string[] args)
{
    foreach(int val in GetFibonacciSeriesList(10))
    {
        Console.WriteLine(val);
    }
}    
public static void Main(string[] args)
{
    // 調用迭代器的方法,從 IEnumerable<T> 取得 IEnumerator<T>
    using (var reader = GetFibonacciSeries(10).GetEnumerator())
    {
        while (reader.MoveNext())
        {
            int val = reader.Current;
            Console.WriteLine(val);
        }
    }
} 

3. finally 的處理

public static IEnumerable<string> Iterator()
{
    try 
    {
        Console.WriteLine("Before first yield");
        yield return "first";
        Console.WriteLine("Between yields");
        yield return "second";
        Console.WriteLine("After yields");    
    }
    finally
    {
        Console.WriteLine("In finally block");
    }
    
}
public static void Main(string[] args)
{
    using (var reader = Iterator().GetEnumerator())
    {
        while (reader.MoveNext())
        {
            string val = reader.Current;
            Console.WriteLine(val);
        }
    }
}   
// Before first yield
// first
// Between yields
// second
// After yields
// In finally block

Share this post on:

Previous
[C#] Partial Type 局部類型
Next
[C#] Delegate 委派