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

当前回答

这里有很多很好的答案,但我想从一个稍微不同的角度来尝试。

你可能熟悉面向对象设计的SOLID原则。总而言之:

S -单一责任原则 O -开/闭原则 利斯科夫替换原理 I -界面隔离原理 D -依赖倒置原理

遵循SOLID原则有助于生成干净、分解良好、内聚和松散耦合的代码。考虑到:

用法与例句:“依赖管理是软件在任何规模上的主要挑战”(唐纳德·克努特)

那么任何有助于依赖管理的东西都是一个巨大的胜利。接口和依赖倒置原则确实有助于将代码与具体类的依赖解耦,因此可以根据行为而不是实现来编写和推理代码。这有助于将代码分解成可以在运行时而不是编译时组合的组件,也意味着这些组件可以很容易地插入和取出,而无需更改其余代码。

Interfaces help in particular with the Dependency Inversion Principle, where code can be componentized into a collection of services, with each service being described by an interface. Services can then be "injected" into classes at runtime by passing them in as a constructor parameter. This technique really becomes critical if you start to write unit tests and use test driven development. Try it! You will quickly understand how interfaces help to break apart the code into manageable chunks that can be individually tested in isolation.

其他回答

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

以下是你的例子:

public interface IFood // not Pizza
{
    public void Prepare();

}

public class Pizza : IFood
{
    public void Prepare() // Not order for explanations sake
    {
        //Prepare Pizza
    }
}

public class Burger : IFood
{
    public void Prepare()
    {
        //Prepare Burger
    }
}

在这种情况下,您可以(也可能会)定义一个Pizza基类并从它们继承。然而,接口允许你做一些其他方式无法做到的事情有两个原因:

一个类可以实现多个接口。它只是定义类必须具有的特性。实现一系列接口意味着一个类可以在不同的地方实现多种功能。 接口可以定义在比类或调用方更大的范围内。这意味着您可以分离功能,分离项目依赖项,并将功能保留在一个项目或类中,并在其他地方实现该功能。

2的一个含义是,您可以更改正在使用的类,只需要它实现适当的接口。

上面的例子没有多大意义。你可以使用类来完成上面所有的例子(如果你想让它只表现为一个契约,那么它就是抽象类):

public abstract class Food {
    public abstract void Prepare();
}

public class Pizza : Food  {
    public override void Prepare() { /* Prepare pizza */ }
}

public class Burger : Food  {
    public override void Prepare() { /* Prepare Burger */ }
}

你会得到和界面相同的行为。您可以创建一个List<Food>,并迭代w/o知道什么类位于顶部。

更合适的例子是多重继承:

public abstract class MenuItem {
    public string Name { get; set; }
    public abstract void BringToTable();
}

// Notice Soda only inherits from MenuItem
public class Soda : MenuItem {
    public override void BringToTable() { /* Bring soda to table */ }
}


// All food needs to be cooked (real food) so we add this
// feature to all food menu items
public interface IFood {
    void Cook();
}

public class Pizza : MenuItem, IFood {
    public override void BringToTable() { /* Bring pizza to table */ }
    public void Cook() { /* Cook Pizza */ }
}

public class Burger : MenuItem, IFood {
    public override void BringToTable() { /* Bring burger to table */ }
    public void Cook() { /* Cook Burger */ }
}

然后你可以把它们都作为菜单项使用,而不用关心它们如何处理每个方法调用。

public class Waiter {
    public void TakeOrder(IEnumerable<MenuItem> order) 
    {
        // Cook first
        // (all except soda because soda is not IFood)
        foreach (var food in order.OfType<IFood>())
            food.Cook();

        // Bring them all to the table
        // (everything, including soda, pizza and burger because they're all menu items)
        foreach (var menuItem in order)
            menuItem.BringToTable();
    }
}

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.