而不是使用ISequence
之类的,我宁愿实现类似的东西:
public static class Sequences {
// Instead of reinveting the wheel (ISequence etc.), let's return
// IEnumerable<long> which is specially designed for such a cases
public static IEnumerable<long> Fibonacci(long first, long second) {
yield return first;
yield return second;
while (true) {
long result = first + second;
first = second;
second = result;
yield return result;
}
}
}
...
// Test: 10 first Fibonacci numbers:
// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
Console.Write(String.Join(", ", Sequences.Fibonacci(1, 2).Take(10)));
...
// Now having Fibonacci as IEnumerable<long>
// you can easily answer a lot of questions via Linq:
long result = Sequences.Fibonacci(1, 2)
.TakeWhile(item => item < 4000000) // up to 4 millions
.Where(item => item % 2 == 0) // take even items only
.Sum(); // sum them up
实现任何接口只是实施接口的缘故是一个不好的做法。
其实,问题2不需要你实现接口,右侧? – Sweeper
接口在那些小应用程序中并非有用。这更多的是关于大型应用程序。 – MajkeloDev
对于这样的问题,你需要研究'递归'而不是接口。当需要与其他模块进行通信时,接口非常有用,因此您可以使用接口来提供一组需要在其中的方法。看看[这里](https://msdn.microsoft.com/en-us/library/3b5b8ezk(v = vs.90).aspx)了解更多关于此事的信息。另外作为一个经验法则,这是决定代码设计的情况,而不是相反的情况。 – npinti