标签:style blog http io color ar os 使用 sp
使用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"; } }
下面给个复杂一点的例子,用迭代器实现返回素数:
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。
标签:style blog http io color ar os 使用 sp
原文地址:http://www.cnblogs.com/laoqi/p/4098209.html