gpt4 book ai didi

c# - 无法实现接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:04 25 4
gpt4 key购买 nike

我是一名 18 岁的 C# 编程学徒(特别是在 OOP“结构”方面)

我目前正在尝试学习接口(interface)的使用/有用性,但是..我很难尝试实际使用接口(interface),我决定开始处理来自 Project Euler 的问题.对于这些问题,我想做的是尝试实现接口(interface)或任何我需要学习的东西,以便我获得一些经验。

我目前在 Problem 2但我想不出一种方法来实现接口(interface)。

所以总的来说,我想问的是,我该怎么做以及如何做(请不要给我最终结果,我只是在寻找一个想法或帮助开始)

我觉得我被困在一个洞里,无法继续,所以我喜欢一些灵感、例子或任何我可以获得好的和简洁信息的东西! :)

提前,非常感谢您的帮助/建设性批评。

-最诚挚的问候,尼克拉斯

最佳答案

Fibonacci 数列是……好吧……一个数列。因此,它可以:

  1. 按索引返回项目

  2. 返回下一个数字

我建议使用单一方法 GetNextElement() 创建接口(interface) ISequence

public interface ISequence
{
int GetNextElement();
}

然后您可以在 FibonacciSequence 类中实现此接口(interface):

public class FibonacciSequence : ISequence
{
private int _lastElement1 = 0;
private int _lastElement2 = 1;

public int GetNextElement()
{
int result = _lastElement1 + _lastElement2;
_lastElement1 = _lastElement2;
_lastElement2 = result;

return result;
}
}

这将允许您实现其他序列,例如等差数列等。

P.S. 我必须承认,为那个特定问题做接口(interface)并不是最好的主意,但出于学习目的 - 为什么不呢! :)

关于c# - 无法实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com