我现在在学习集合,书上的这个例子,请问下为什么说Primes类不包含GetEnumberator的公共定义,以至Main函数里的foreach不能用Primes的变量?
谢谢了!
[code]
public class Primes
{
private long min, max;
public Primes()
: this(2, 100)
{
}
public Primes(long minimum, long maximum)
{
if (min < 2)
{
min = 2;
}
min = minimum;
max = maximum;
}
public IEnumerator GetEnumberator()
{
for (long possiblePrime = min; possiblePrime <= max; possiblePrime++)
{
bool isPrime = true;
for (long possibleFactor = 2; possiblePrime <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
{
long remainderAfterDivision = possiblePrime % possibleFactor;
if (remainderAfterDivision == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
yield return possiblePrime;
}
}
}
}
[/code][code]
static void Main(string[] args)
{
Primes primesForm2To1000 = new Primes(2, 1000);
foreach (long i in primesForm2To1000)
Console.WriteLine("{0}", i);
Console.ReadKey();
}
[/code]
谢谢了!
[code]
public class Primes
{
private long min, max;
public Primes()
: this(2, 100)
{
}
public Primes(long minimum, long maximum)
{
if (min < 2)
{
min = 2;
}
min = minimum;
max = maximum;
}
public IEnumerator GetEnumberator()
{
for (long possiblePrime = min; possiblePrime <= max; possiblePrime++)
{
bool isPrime = true;
for (long possibleFactor = 2; possiblePrime <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
{
long remainderAfterDivision = possiblePrime % possibleFactor;
if (remainderAfterDivision == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
yield return possiblePrime;
}
}
}
}
[/code][code]
static void Main(string[] args)
{
Primes primesForm2To1000 = new Primes(2, 1000);
foreach (long i in primesForm2To1000)
Console.WriteLine("{0}", i);
Console.ReadKey();
}
[/code]
{
private long min, max;
public Primes()
: this(2, 100)
{
}
public Primes(long minimum, long maximum)
{
if (min < 2)
{
min = 2;
}
min = minimum;
max = maximum;
}
public IEnumerator GetEnumberator()
{
for (long possiblePrime = min; possiblePrime <= max; possiblePrime++)
{
bool isPrime = true;
for (long possibleFactor = 2; possiblePrime <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
{
long remainderAfterDivision = possiblePrime % possibleFactor;
if (remainderAfterDivision == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
yield return possiblePrime;
}
}
}
}
static void Main(string[] args)
{
Primes primesForm2To1000 = new Primes(2, 1000);
foreach (long i in primesForm2To1000)
Console.WriteLine("{0}", i);
Console.ReadKey();
}