使用foreach循环是有IEnumerator接口来实现的,IEnumerator即实现了迭代器,在foreach中如何迭代一个集合arrayList呢?
迭代器的实现例子:
class Program { public static void Main(string[] args) { foreach (string str in SimpleList()) { Console.WriteLine(str); } Console.ReadKey(); } public static IEnumerable SimpleList() { yield return "1"; yield return "2"; yield return "3"; } }这样我们就实现了一个最简单的迭代器。结果为:QQ截图20141114211249" border="0" alt="QQ截图20141114211249" src="/Upload/Images/2014111423/4D5D398EB6A9AAB9.png" width="135" height="97" />
下面给个复杂一点的例子,用迭代器实现返回素数:
public static void Main(string[] args) { Primes primesFrom2TO1000 = new Primes(2, 1000); foreach (long i in primesFrom2TO1000) { Console.Write("{0}", i); } }
public class Primes { private long min; private long max; public Primes() : this(2, 200) { } public Primes(long minimum, long maximum) { if (minimum < 2) { min = 2; } else { min = minimum; } max = maximum; } public System.Collections.IEnumerator GetEnumerator()//返回类型为一个迭代器 { for (long possiblePrime = min; possiblePrime <= max; possiblePrime++) { bool isPrime = true; for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++) { long remainderAfterDivsion = possiblePrime % possibleFactor; if (remainderAfterDivsion == 0) { isPrime = false; break; } } if (isPrime) { yield return possiblePrime;//为素数,返回之 } } } }
结果为:
迭代器返回的类型有两种:IEnumberable和IEnumerator。