我真的不明白接口存在的原因。据我所知,这是c#中不存在的多继承的一种工作(至少我是这么被告知的)。

我所看到的是,您预定义了一些成员和函数,然后必须在类中再次重新定义它们。从而使接口成为冗余。它只是感觉像句法……嗯,垃圾对我来说(请没有冒犯的意思。Junk是指无用的东西)。

在下面的例子中,我将创建一个名为Pizza的基类,而不是一个接口。

简单示例(取自不同的堆栈溢出贡献)

public interface IPizza
{
    public void Order();
}

public class PepperoniPizza : IPizza
{
    public void Order()
    {
        //Order Pepperoni pizza
    }
}

public class HawaiiPizza : IPizza
{
    public void Order()
    {
        //Order HawaiiPizza
    }
}

当前回答

你会得到界面,当你需要他们:)你可以研究例子,但你需要的是啊哈!效果才能真正得到他们。

现在您已经知道了接口是什么,只需编写没有接口的代码。您迟早会遇到一个问题,在这个问题中使用接口将是最自然的事情。

其他回答

接口用于应用不同类之间的连接。例如,你有一个关于汽车和树的类;

public class Car { ... }

public class Tree { ... }

您希望为这两个类添加一个可燃功能。但是每个职业都有自己的燃烧方式。所以你只要做;

public class Car : IBurnable
{
public void Burn() { ... }
}

public class Tree : IBurnable
{
public void Burn() { ... }
}

考虑到你不能在c#中使用多重继承,然后再看看你的问题。

你会得到界面,当你需要他们:)你可以研究例子,但你需要的是啊哈!效果才能真正得到他们。

现在您已经知道了接口是什么,只需编写没有接口的代码。您迟早会遇到一个问题,在这个问题中使用接口将是最自然的事情。

我很惊讶,没有多少文章包含一个最重要的接口原因:设计模式。这是使用契约的更大的前景,尽管它是机器代码的语法装饰(老实说,编译器可能会忽略它们),但抽象和接口对于OOP、人类理解和复杂的系统架构来说是至关重要的。

让我们把披萨的比喻扩大到一顿完整的大餐。对于所有的食物类别,我们仍然有核心的Prepare()接口,但我们也有针对课程选择(前菜、主菜、甜点)的抽象声明,以及针对食物类型(咸的/甜的、素食的/非素食的、无麸质的等)的不同属性。

基于这些规范,我们可以实现抽象工厂模式来概念化整个过程,但是使用接口来确保只有基础是具体的。其他一切都可以变得灵活或鼓励多态,同时在实现iccourse接口的不同Course类之间保持封装。

如果我有更多的时间,我想画一个完整的例子,或者有人可以为我扩展它,但总的来说,c#接口将是设计这类系统的最佳工具。

To me an advantage/benefit of an interface is that it is more flexible than an abstract class. Since you can only inherit 1 abstract class but you can implement multiple interfaces, changes to a system that inherits an abstract class in many places becomes problematic. If it is inherited in 100 places, a change requires changes to all 100. But, with the interface, you can place the new change in a new interface and just use that interface where its needed (Interface Seq. from SOLID). Additionally, the memory usage seems like it would be less with the interface as an object in the interface example is used just once in memory despite how many places implement the interface.