C#实现一个迭代器

GK_2014 GK_2014 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
刚刚学习C#,看着书上的例子敲代码,运行了下报错如下:
错误 1 “CH11Ex03.Primes”不包含“GetEnumerator”的公共定义,因此 foreach 语句不能作用于“CH11Ex03.Primes”类型的变量

这个控制台程序是找出2~100之间的素数,并打印出来。
下面是新建的Primes类

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CH11Ex03
{
public class Primes
{
private long min;
private long max;

public Primes(): this(2, 100)
{

}

public Primes(long Min, long Max)
{
if (min<2)
{
min = Min;
}
else
{
min = Min;
}
max = Max;
}

public IEnumerator GetIEnumerator()
{
for (long possiblePrimer = min; possiblePrimer <= max; possiblePrimer++ )
{
bool flag = true;
for (long factor = 2; factor < (long)Math.Floor(Math.Sqrt(possiblePrimer)); factor++)
{
if (0 == possiblePrimer%factor)
{
flag = false;
break;
}
}
if (flag)
{
yield return possiblePrimer;
}
}
}
}
}


下面这段是主程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CH11Ex03
{
class Program
{
static void Main(string[] args)
{
Primes myPrimes = new Primes(2, 100);
foreach (long num in myPrimes)
{
Console.Write("{0}", num);
}

Console.ReadKey();
}
}
}


请达人帮我看看哪里有问题?
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
GK_2014
C# 111,128 成员 642,537 内容