A generator is a special routine that can be used to control the iteration behaviour of a loop
以C#為程式語言示範,假設沒有控制Iterator的話,印出一到一百間所有質數,我們會這麼寫。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
static IList<int> GeneratorPrimes() { var result = new List<int>(); for (int i = 2; i <= 100; i++) { bool flag = true; for (int j = 2; j * j <= i && flag; j++) if (i % j == 0) flag = false; if (flag) result.Add(i); } return result; } IList<int> ans = GeneratorPrimes(); foreach (var item in ans) { Console.WriteLine(" {0} ", item); }
public class PrimesGenerator : IEnumerator<int> { int current, next; public PrimesGenerator() { Reset(); } private void calcNext() { for (next++; ; next++) { bool flag = true; for (int i = 2; flag && i * i <= next; i++) if (next % i == 0) flag = false; if (flag) break; } } public bool MoveNext() { return current < 100; } public void Dispose() { } public int Current { get { int ret = current; current = next; calcNext(); return ret; } } object System.Collections.IEnumerator.Current { get { int ret = current; current = next; calcNext(); return ret; } } public void Reset() { current = 2; next = 3; } } public class IEnumerablePrimes : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { return new PrimesGenerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static IEnumerable<int> GeneratorPrime() { return new IEnumerablePrimes(); }
public static IEnumerable<int> GeneratorPrime() { for (int i = 2; i <= 100; i++) { bool flag = true; for (int j = 2; j * j <= i && flag; j++) if (i % j == 0) flag = false; if (flag) yield return i; } }