继承类和支持接口问题
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class Primes : IEnumerable
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public Primes(long minimum, long maximum)
{
min = minimum;
if (min < 2)
{
min = 2;
}
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;
}
}
}
}
}
=======================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class Primes
{
private long min;
private long max;
public Primes()
: this(2, 100)
{
}
public Primes(long minimum, long maximum)
{
min = minimum;
if (min < 2)
{
min = 2;
}
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;
}
}
}
}
}
========================================
这2段代码结果是一样的.区别是第一段代码支持IEnumerable接口,而第二段代码没有支持IEnumerable接口...
想问的是:
为什么不支持IEnumerable接口,怎么能实现IEnumerator GetEnumerator()方法?
这是一个例子,还好多不继承类也不支持接口都能实现他们的方法...我不理解?
------解决方案--------------------如果继承接口,当然要实现接口的函数,名字改了就不是实现了
------解决方案--------------------即使不实现IEnumerable,当你在使用foreach的时候其实内部还是在调用GetEnumerator方法,你可以把GetEnumerator方法名字改掉,就运行不了foreach了。
试想,一个项目即使不用一个接口也能够实现,但是接