我真的不明白接口存在的原因。据我所知,这是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
    }
}

当前回答

类比简单解释

无接口(例1):

无接口(例2):

有接口:

需要解决的问题:多态性的目的是什么?

比方说,我是一个建筑工地的领班。我不知道哪个商人会走进来。但我告诉他们该怎么做。

如果是木匠,我会说:搭建木质脚手架。 如果是管道工,我会说:安装管道 如果是人民党政府官员,我说,三袋现金,先生。

上述方法的问题在于:(1)我必须知道谁会走进那扇门,并且根据是谁,我必须告诉他们该做什么。这通常会使代码更难维护或更容易出错。

知道该做什么的含义:

This means if the carpenter's code changes from: BuildScaffolding() to BuildScaffold() (i.e. a slight name change) then I will have to also change the calling class (i.e. the Foreperson class) as well - you'll have to make two changes to the code instead of (basically) just one. With polymorphism you (basically) only need to make one change to achieve the same result. Secondly you won't have to constantly ask: who are you? ok do this...who are you? ok do that.....polymorphism - it DRYs that code, and is very effective in certain situations: with polymorphism you can easily add additional classes of tradespeople without changing any existing code. (i.e. the second of the SOLID design principles: Open-close principle).

解决方案

想象一下这样一个场景:无论谁走进来,我都可以说:“Work()”,他们做着自己擅长的工作:管道工处理管道,电工处理电线,官僚可能专门负责受贿,为其他人做双倍的工作。

这种方法的好处是:(i)我不需要确切地知道谁会走进那扇门——我只需要知道他们是一种手工工人,他们会工作,其次,(ii)我不需要知道任何关于特定行业的信息。手工工人会处理的。

所以不要这样:

if(electrician) then  electrician.FixCablesAndElectricity() 

if(plumber) then plumber.IncreaseWaterPressureAndFixLeaks() 

if(keralaCustoms) then keralaCustoms.askForBribes() 

我可以这样做:

ITradesman tradie = Tradesman.Factory(); // in reality i know it's a plumber, but in the real world you won't know who's on the other side of the tradie assignment.

tradie.Work(); // and then tradie will do the work of a plumber, or electrician etc. depending on what type of tradesman he is. The foreman doesn't need to know anything, apart from telling the anonymous tradie to get to Work()!!

有什么好处?

这样做的好处是,如果木匠等特定的工作要求发生了变化,那么领班就不需要改变他的代码——他不需要知道或关心。重要的是木匠知道Work()是什么意思。其次,如果一种新型的建筑工人来到工地上,那么工头不需要知道任何关于贸易的事情——工头所关心的是建筑工人(.e。焊工、上釉工、瓦工等)可以完成一些工作。

总结

界面允许您让人完成分配给他们的工作,而不需要您确切地知道他们是谁或他们可以做什么。这允许您轻松地添加新的(交易)类型,而无需更改现有的代码(从技术上讲,您确实更改了一点点),这是面向对象方法相对于更函数式编程方法的真正好处。

如果你不理解上面的任何内容,或者不清楚,请在评论中提问,我会尽量让答案更好。

其他回答

I share your sense that Interfaces are not necessary. Here is a quote from Cwalina pg 80 Framework Design Guidelines "I often here people saying that interfaces specify contracts. I believe this a dangerous myth. Interfaces by themselves do not specify much. ..." He and co-author Abrams managed 3 releases of .Net for Microsoft. He goes on to say that the 'contract' is "expressed" in an implementation of the class. IMHO watching this for decades, there were many people warning Microsoft that taking the engineering paradigm to the max in OLE/COM might seem good but its usefulness is more directly to hardware. Especially in a big way in the 80s and 90s getting interoperating standards codified. In our TCP/IP Internet world there is little appreciation of the hardware and software gymnastics we would jump through to get solutions 'wired up' between and among mainframes, minicomputers, and microprocessors of which PCs were just a small minority. So coding to interfaces and their protocols made computing work. And interfaces ruled. But what does solving making X.25 work with your application have in common with posting recipes for the holidays? I have been coding C++ and C# for many years and I never created one once.

class Program {
    static void Main(string[] args) {
        IMachine machine = new Machine();
        machine.Run();
        Console.ReadKey();
    }

}

class Machine : IMachine {
    private void Run() {
        Console.WriteLine("Running...");
    }
    void IMachine.Run() => Run();
}

interface IMachine
{
    void Run();
}

让我从另一个角度来描述一下。让我们根据上面的例子来创建一个故事;

程序、机器和IMachine是我们故事的演员。程序想要运行,但它没有这个能力,而机器知道如何运行。机器和IMachine是最好的朋友,但程序和机器没有说话的关系。于是程序和IMachine做了一个交易,决定IMachine通过观察机器(就像一个反射器)来告诉程序如何运行。

Program在IMachine的帮助下学习如何运行。

接口提供通信和开发松散耦合的项目。

PS:我把具体类的方法作为私有。我在这里的目标是通过防止访问具体的类属性和方法来实现松耦合,只允许通过接口访问它们。(所以我明确地定义了接口的方法)。

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

public class Car { ... }

public class Tree { ... }

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

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

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

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

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

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

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

Pizza示例很糟糕,因为您应该使用一个处理排序的抽象类,而pizzas应该重写Pizza类型。

当您有一个共享属性,但是您的类从不同的地方继承,或者当您没有任何可以使用的公共代码时,您可以使用接口。例如,这是用过的东西,可以被处置为IDisposable,你知道它会被处置,你只是不知道当它被处置时会发生什么。

接口只是一个契约,它告诉你一个对象可以做一些事情,什么样的参数和期望什么样的返回类型。