C#基礎:迭代器原理
阿新 • • 發佈:2018-12-20
在迭代器塊中,使用yield關鍵字返回給foreach迴圈中使用的值,下面是迭代器的原理。SimpleList()是迭代器塊。
- public static IEnumerable SimpleList()//迭代器使用yield return返回值給foreach
- {
- yield return "string 1";
- yield return "string 2";
- yield return "string 3";
- }
- static void Main(string[] args){
- foreach(string a in SimpleList){
- Console.WriteLine(a);
- }
- }
例項程式碼如下,使用迭代器列印素數。素數是隻能被1和他本身整除的數,也叫質數。
//迭代器
- public class Primes {//迭代器類
- private int min;//最小值
- private int max;//最大值
- public Primes() : this(2, 100) { }//預設構造(2,100)
- public Primes(int min,int max) {
- if (min < 2)
- {
- this.min = 2;
- }
- else {
- this.min = min;
- }
- this.max = max;
- }
- public IEnumerator GetEnumerator() {//迭代器塊
- bool isPrime = true;
- for (int i = min; i <= max; i++)//迴圈輸出
- {
- for (int j = 2; j <i; j++)//判斷能否能被2--->i-1之間的數整除
- {
- if (i % j == 0)//餘數是否為0,能整除,就不是素數
- {
- isPrime = false;
- break;
- }
- else if(i%j!=0){
- isPrime = true;
- }
- }
- if (isPrime)
- {
- yield return i;//返回給foreach要使用的值
- }
- }
- }
- }
//Main()方法
- static void Main(string[] args){
- Primes aa=new Primes(2,1000);
- Primes bb=new Primes();//預設(2,100)
- foreach(string a in aa){
- Console.Write(a+" ");
- foreach(string b in bb){
- Console.Write(a+" ");
- }
- }
- }