在迭代器块中,使用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+" ");
- }
- }
- }

本文介绍C#中的迭代器实现原理,通过具体示例展示如何使用yield关键字返回值给foreach循环。同时,深入解析了利用迭代器打印指定范围内素数(质数)的代码实现。
1万+

被折叠的 条评论
为什么被折叠?



