What is the difference between an Iterator and a Generator?

后端 未结 9 1840
感情败类
感情败类 2020-12-07 15:49

What is the difference between an Iterator and a Generator?

9条回答
  •  醉话见心
    2020-12-07 16:35

    A generator is an implementation of an iterator. It is typically a routine that yields multiple values to its caller as opposed to just one.

    In c#

    // yield-example.cs
    using System;
    using System.Collections;
    public class List
    {
        public static IEnumerable Power(int number, int exponent)
        {
            int counter = 0;
            int result = 1;
            while (counter++ < exponent)
           {
                result = result * number;
                yield return result;
        }
    }
    
    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }
    }
    

    See Wikipedia's entry

提交回复
热议问题