日期:2014-05-18 浏览次数:20882 次
public class Primes { private long min; private long max; public Primes() : this(2, 100) { } public Primes(long minimum, long maximum) { if (minimum < 2) min = 2; else min = minimum; max = maximum; } public 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 remainderAfterDivision = possiblePrime % possibleFactor; if (remainderAfterDivision == 0) { isPrime = false; break; } } if (isPrime) { yield return possiblePrime; } } } } class Program { static void Main(string[] args) { Primes primesFrom2To1000 = new Primes(1000000000000, 1000000010000); IEnumerator myEnumerator = primesFrom2To1000.GetEnumerator(); myEnumerator.MoveNext(); myEnumerator.MoveNext(); //foreach (long i in primesFrom2To1000) // Console.Write("{0} ", i); Console.ReadKey(); } }
namespace yieldReturnPractice { class Program { static void Main(string[] args) { List<string> docs1 = new List<string>(); docs1.Add("1"); docs1.Add("2"); docs1.Add("3"); docs1.Add("4"); docs1.Add("5"); foreach (var item in Documents1(docs1)) { Console.Write(" {0} ", item); } Console.Write("\n***********************************\n"); foreach (var item in Documents2(docs1)) { Console.Write(" {0} ", item); } Console.ReadKey(); } static IEnumerable Documents1(List<string> docs) { foreach (var item in docs) { if (item != "4") yield return item; } Console.Write(" {0} ", "Holle Danny"); } static IEnumerable Documents2(List<string> docs) { foreach (var item in docs) { if (item != "4") yield return item; else yield break; } Console.Write(" {0} ", "Holle Danny"); } } }
------解决方案--------------------
编译器会创建一个实现了IEnumertor接口的类,并将其返回