简体   繁体   English

接口和类有什么区别,为什么我可以在类中直接实现方法时使用接口?

[英]What is the difference between an interface and a class, and why I should use an interface when I can implement the methods directly in the class?

I am aware that this is a very basic question, but an interviewer asked me in a very trick way and I was helpless :(我知道这是一个非常基本的问题,但是面试官问了我很狡猾的方式,我很无助:(

I know only material or theoretical definition for an interface and also implemented it in many projects I worked on.我只知道接口的材料或理论定义,并且还在我参与的许多项目中实现了它。 But I really don't understand why and how is this useful.但我真的不明白这为什么以及如何有用。

I also don't understand one thing in interface.我也不明白界面中的一件事。 ie for example, we use即例如,我们使用

conn.Dispose(); in finally block.在 finally 块中。 But I don't see that class is implementing or inheriting IDisposable interface ( SqlConnection ) class I mean.但我没有看到该类正在实现或继承IDisposable接口( SqlConnection )类,我的意思是。 I am wondering how I can just call the method name.我想知道如何只调用方法名称。 Also in the same thing, I am not understanding how Dispose method works as because, we need to implement the function body with our own implementation for all interface methods.同样在同一件事上,我不理解 Dispose 方法是如何工作的,因为我们需要使用我们自己的所有接口方法实现来实现函数体。 So how Interfaces are accepted or named as contracts?那么接口是如何被接受或命名为契约的呢? These questions kept on rolling in my mind till now and frankly I never saw any good thread that would explain my questions in a way that I can understand.直到现在,这些问题一直在我的脑海中盘旋,坦率地说,我从未见过任何能以我能理解的方式解释我的问题的好线索。

MSDN as usual looks very scary and no single line is clear there ( Folks, kindly excuse who are into high level development, I strongly feel that any code or article should reach the mind of anyone who see it, hence like many others say, MSDN is not of use ).像往常一样 MSDN 看起来非常可怕,那里没有任何一行是清楚的(伙计们,请原谅那些从事高级开发的人,我强烈认为任何代码或文章都应该到达任何看到它的人的脑海中,因此就像许多其他人所说的,MSDN没有用)。

The interviewer said:面试官说:

He has 5 methods and he is happy to implement it in the class directly, but if you have to go for Abstract class or interface, which one you choose and why ?他有 5 个方法,他很乐意直接在类中实现它,但是如果您必须使用抽象类或接口,您选择哪一个,为什么? I did answered him all the stuffs that I read in various blog saying advantage and disadvantage of both abstract class and interface, but he is not convinced, he is trying to understand "Why Interface" in general.我确实回答了他在各种博客中读到的所有内容,说抽象类和接口的优缺点,但他不相信,他试图理解“为什么是接口”。 "Why abstract class" in general even if I can implement the same methods only one time and not gona change it. “为什么是抽象类”,即使我只能实现一次相同的方法并且不会改变它。

I see no where in net, I could get an article that would explain me clearly about interfaces and its functioning.我在网络上看不到任何地方,我可以得到一篇文章,可以清楚地解释接口及其功能。 I am one of those many programmers, who still dont know about interfaces (I know theoretical and methods I used) but not satisfied that I understood it clearly.我是众多程序员中的一员,他们仍然不了解接口(我知道我使用的理论和方法)但不满足于我清楚地理解它。

Interfaces are excellent when you want to create something like it:当您想创建类似的东西时,接口非常好:

using System;

namespace MyInterfaceExample
{
    public interface IMyLogInterface
    {
        //I want to have a specific method that I'll use in MyLogClass
        void WriteLog();       
    }

    public class MyClass : IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyClass was Logged");
        }
    }

    public class MyOtherClass : IMyLogInterface
    {

        public void WriteLog()
        {
            Console.Write("MyOtherClass was Logged");
            Console.Write("And I Logged it different, than MyClass");
        }
    }

    public class MyLogClass
    {
        //I created a WriteLog method where I can pass as a parameter any object that implements IMyLogInterface.
        public static void WriteLog(IMyLogInterface myLogObject)
        {
            myLogObject.WriteLog(); //So I can use WriteLog here.
        }
    }

    public class MyMainClass
    {
        public void DoSomething()
        {
            MyClass aClass = new MyClass();
            MyOtherClass otherClass = new MyOtherClass();

            MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation
            MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log.
        }
    }
}

In my example, I could be a developer who writes MyLogClass , and the other developers, could create their classes, and when they wanted to log, they implement the interface IMyLogInterface .在我的示例中,我可以是编写MyLogClass的开发人员,而其他开发人员可以创建他们的类,当他们想要记录时,他们实现接口IMyLogInterface It is as they were asking me what they need to implement to use WriteLog() method in MyLogClass .就像他们问我在MyLogClass使用WriteLog()方法需要实现什么MyLogClass The answer they will find in the interface.他们会在界面中找到答案。

One reason I use interfaces is because it increases the flexibility of the code.我使用接口的原因之一是因为它增加了代码的灵活性。 Let's say we got a method that takes an object of class type Account as parameter, such as:假设我们得到了一个以类类型 Account 作为参数的方法,例如:

public void DoSomething(Account account) {
  // Do awesome stuff here.
}

The problem with this, is that the method parameter is fixed towards an implementation of an account.问题在于,方法参数是针对帐户的实现而固定的。 This is fine if you would never need any other type of account.如果您永远不需要任何其他类型的帐户,这很好。 Take this example, which instead uses an account interface as parameter.以这个例子为例,它使用一个帐户接口作为参数。

public void DoSomething(IAccount account) {
  // Do awesome stuff here.
}

This solution is not fixed towards an implementation, which means that I can pass it a SuperSavingsAccount or a ExclusiveAccount (both implementing the IAccount interface) and get different behavior for each implemented account.此解决方案不是针对实现而固定的,这意味着我可以向它传递 SuperSavingsAccount 或 ExclusiveAccount(均实现 IAccount 接口)并为每个实现的帐户获得不同的行为。

Interfaces are contracts that implementers must follow.接口是实现者必须遵守的契约。 Abstract classes allow contracts plus shared implementations - something that Interfaces cannot have.抽象类允许契约加上共享实现——这是接口不能拥有的。 Classes can implement and inherit multiple interfaces.类可以实现和继承多个接口。 Classes can only extend a single abstract class.类只能扩展一个抽象类。

Why Interface为什么是接口

  • You don't have default or shared code implementation您没有默认或共享的代码实现
  • You want to share data contracts (web services, SOA)您想要共享数据契约(Web 服务、SOA)
  • You have different implementations for each interface implementer ( IDbCommand has SqlCommand and OracleCommand which implement the interface in specific ways )每个接口实现者都有不同的实现( IDbCommandSqlCommandOracleCommand ,它们以特定方式实现接口
  • You want to support multiple inheritance .您希望支持多重继承

Why Abstract为什么要抽象

在此处输入图片说明

So in this example, the PowerSocket doesn't know anything else about the other objects.所以在这个例子中,PowerSocket 对其他对象一无所知。 The objects all depend on Power provided by the PowerSocket, so they implement IPowerPlug, and in so doing they can connect to it.这些对象都依赖于 PowerSocket 提供的 Power,因此它们实现了 IPowerPlug,这样它们就可以连接到它。

Interfaces are useful because they provide contracts that objects can use to work together without needing to know anything else about each other.接口很有用,因为它们提供了对象可以用来协同工作的契约,而无需了解彼此的任何其他信息。

In one word - because of Polymorphism !一句话—​​—因为多态

If you "Program to an Interface, not an Implementation" than you can inject different objects which share the same interface(type) into the method as an argument.如果您“为接口编程,而不是实现”,那么您可以将共享相同接口(类型)的不同对象作为参数注入到方法中。 This way your method code is not coupled with any implementation of another class which means it's always open to work with newly created objects of the same interface.这样您的方法代码就不会与另一个类的任何实现耦合,这意味着它始终可以使用相同接口的新创建的对象。 (Open/Close Principle) (开闭原则)

  • Look into Dependency Injection and definitely read Design Patterns - Elements of Reusable Object-Oriented Software by GOF.研究依赖注入,一定要阅读 GOF 的Design Patterns - Elements of Reusable Object-Oriented Software

I believe that many blood was already spilled in asking this questions, and many tries to resolve this issues by explaining robot-like terms that no normal human can understand.我相信在问这个问题时已经流了很多血,许多人试图通过解释正常人无法理解的类似机器人的术语来解决这个问题。

So First.所以首先。 to learn why interface and why abstract you need to learn what are them for.要了解为什么接口和为什么抽象,您需要了解它们的用途。 I personnaly learned this two when applying Factory Class.我个人在申请 Factory Class 时学到了这两个。 you find a good tuturial on this link在这个链接上找到了一个很好的教程

Now let's dig-in base on the link I already gave.现在让我们根据我已经给出的链接进行挖掘。

You have Vehicle class that might change upon user requirement (like adding Truck , Tank , Airplane , etc. And given we have您有可能会根据用户要求更改的Vehicle类(例如添加TruckTankAirplane等。鉴于我们有

public class clsBike:IChoice
{
   #region IChoice Members
    public string Buy()
    {
       return ("You choose Bike");
    }
    #endregion
}

and

public class clsCar:IChoice
{
   #region IChoice Members
    public string Buy()
    {
       return ("You choose Car");
    }
    #endregion
}

and both has Contract IChoice that simply say My Class should have Buy method并且两者都有 Contract Ichoice ,只是说 My Class 应该有 Buy 方法

public interface IChoice
{
    string Buy();
}

Now, you see, that interface only enforce the method Buy() but let the inherited class decide what to do when they implement it.现在,您会看到,该接口仅强制执行Buy()方法,但让继承的类决定在实现它时要执行的操作。 This is the limitation of Interface, using purely interface, you might end up repeating some task that we can implement automatically using abstact.这是接口的局限性,使用纯接口,您可能最终会重复一些我们可以使用 abstact 自动实现的任务。 On our example let say, buying each vehicle has a discount.在我们的例子中,假设购买每辆车都有折扣。

public abstract class Choice
{
    public abstract string Discount { get; }
    public abstract string Type { get; }
    public string Buy()
    {
       return "You buy" + Type + " with " + Discount;
}
public class clsBike: Choice
{
    public abstract string Discount { get { return "10% Discount Off"; } }
    public abstract string Type { get { return "Bike"; } }
}

public class clsCar:Choice
{
    public abstract string Discount { get { return " $15K Less"; } }
    public abstract string Type { get { return "Car"; } }
}

Now using the Factory Class, you can achieve the same thing but in using abstract, you let the base class execute the Buy() method.现在使用工厂类,您可以实现相同的目的,但是在使用抽象时,您让基类执行Buy()方法。

In Summary : Interface contracts let the inherit class do the implementation while Abstract class Contracts may initialize the implementation (which can override by Inherit class)总结:接口契约让继承类做实现,而抽象类契约可以初始化实现(可以被继承类覆盖)

C# doesn't have duck typing - just because you know a certain method is implemented across a set of concrete classes doesn't mean you can treat them all the same with regards to calling that method. C# 没有鸭子类型 - 仅仅因为您知道某个方法是跨一组具体类实现的,并不意味着您可以在调用该方法时对它们一视同仁。 Implementing an interface allows you to treat all classes implementing it as the same type of thing, with regards to what that interface defines.实现接口允许您将实现它的所有类视为相同类型的事物,这与该接口定义的内容有关。

This is an easy example:这是一个简单的例子:

Both of Array and List implement the interface IList . ArrayList实现了接口IList Below we have a string[] and a List<string> and manipulate both of them with only one method by using IList :下面我们有一个string[]和一个List<string>并使用IList仅用一种方法操作它们:

string[] myArray = { "zero", "one", "two", "three", "four"};
List<string> myList = new List<string>{ "zero", "one", "two", "three"};

//a methode that manipulates both of our collections with IList
static void CheckForDigit(IList collection, string digit)
{
    Console.Write(collection.Contains(digit));  //checks if the collection has a specific digit
    Console.Write("----");
    Console.WriteLine(collection.ToString()); //writes the type of collection
}

static void Main()
{
    CheckForDigit(myArray, "one");   //True----System.String[]
    CheckForDigit(myList, "one");   //True----System.Collections.Generic.List`1[System.String]



//Another test:

    CheckForDigit(myArray, "four");   //True----System.String[]
    CheckForDigit(myList, "four");   //false----System.Collections.Generic.List`1[System.String]
}

With an interface you can do the following:使用界面,您可以执行以下操作:

1) Create segregated interfaces which offer differing cuts of your implementation, allowing for a more cohesive interface. 1)创建分离的接口,提供不同的实现方式,允许一个更有凝聚力的接口。

2) Allow for multiple methods with the same name between interfaces, because hey, you have no conflicting implementation, just a signature. 2)允许接口之间有多个同名方法,因为嘿,你没有冲突的实现,只有一个签名。

3) You can version and hive off your interface independantly of your implementation, ensuring a contract is met. 3) 你可以独立于你的实现来版本化和分离你的接口,确保满足合同。

4) Your code can rely on abstraction rather than concretion, allowing for smart dependency injection, including injecting test Mocks etc. 4) 你的代码可以依赖抽象而不是具体,允许智能依赖注入,包括注入测试 Mocks 等。

There are many more reasons I'm sure, these are just a few.我敢肯定还有更多的原因,这些只是其中的几个。

An abstract class allows you to have a partially concrete base to work from, this is not the same as an interface but has its own qualities such as the ability to create partial implementation using the template method pattern.抽象类允许你有一个部分具体的基础来工作,这与接口不同,但有它自己的特性,比如使用模板方法模式创建部分实现的能力。

Interfaces are to make an abstraction (an archetype) of the abstraction (the classes) of the reality (the objects).接口是对现实(对象)的抽象(类)进行抽象(原型)。

Interfaces are to specify contract terms without providing implementation provided by classes.接口是在不提供类提供的实现的情况下指定合同条款。

Interfaces are specifications:接口是规格:

  • Interfaces are design time artifacts to specify the immobile behavior of the concept as it is alone and static.接口是设计时工件,用于指定概念的固定行为,因为它是单独的和静态的。

  • Classes are implementation time artifacts to specify the mobile structure of the reality as it interacts and move.类是实现时间工件,用于指定现实交互和移动时的移动结构。

What is an interface?什么是接口?

When you observe a cat you can say that it is an animal that has four paws, a head, a trunk, a tail and hair.当你观察一只猫时,你可以说它是一种有四只爪子、一个头、一个躯干、一条尾巴和一根毛的动物。 You can see that he can walk, run, eat and meow.你可以看到他会走路、跑步、吃饭和喵喵叫。 And so on.等等。

You have just defined an interface with its properties and its operations.您刚刚定义了一个带有属性和操作的接口。 As such you have not defined any modus operandi, but only features and capabilities without knowing how things work: you have defined abilities and distinctions.因此,您没有定义任何作案手法,而只是定义了特性和能力,而不知道事情是如何运作的:您已经定义了能力和区别。

As such it is not really yet a class even though in UML we call this a class in a class diagram because we can define privates and protected members to begin having a deep view of the artifact.因此,尽管在 UML 中我们称其为类图中的类,但它实际上还不是一个类,因为我们可以定义私有成员和受保护成员以开始深入了解工件。 Do not be confused here because in UML an interface is a slightly different thing that an interface in C#: it is like a partial access point to the abstraction atom.不要在这里混淆,因为在 UML 中,接口与 C# 中的接口略有不同:它就像是抽象原子的部分访问点。 As such we said that a class can implements multiple interfaces.因此我们说一个类可以实现多个接口。 As such it is the same thing, but not, because interfaces in C# are both used to abstract the abstraction and to limit this abstraction as an access point.因此,它是同一件事,但不是,因为 C# 中的接口既用于抽象抽象,又用于将此抽象限制为访问点。 It's two different uses.这是两种不同的用途。 Thus a class in UML represents a full coupling interface to a programming class, whereas an UML interface represents a decoupling interface of a section of a programming class.因此,UML 中的类表示与编程类的完全耦合接口,而 UML 接口表示编程类的一部分的解耦接口。 Indeed, the class diagram in UML does not take care of the implementation and all its artifacts are at the programming interface level.实际上,UML 中的类图并不关心实现,它的所有工件都在编程接口级别。 While we map UML classes to programming classes, it is a transposition of abstract abstraction into concrete abstraction.当我们将 UML 类映射到编程类时,它是抽象抽象到具体抽象的转换。 There is a subtlety that explains the dichotomy between the field of design and the field of programming.有一种微妙之处可以解释设计领域和编程领域之间的二分法。 So a class in UML is a programming class from the point of view of a programming interface while considering inner hidden things.因此,从编程接口的角度来看,UML 中的类是一个编程类,同时考虑了内部隐藏的事物。

Interfaces also allow to simulate multiple inheritance when not available in an awkward way.接口还允许在以笨拙的方式不可用时模拟多重继承。 For example, the cat class will implement the cat interface that derives itself from the animal interface.例如,cat 类将实现从动物接口派生的 cat 接口。 This cat class will also implement these interfaces: walk, run, eat and make a sound.这个 cat 类还将实现这些接口:walk、run、eat 和 make a sound。 This compensates for the absence of multiple inheritance at the class level, but each time you need to reimplement everything and you can not factor the reality at best like the reality itself do it.这弥补了类级别多重继承的缺失,但是每次您需要重新实现所有内容时,您最多不能像现实本身那样考虑现实。

To understand that we can refer to Pascal Object coding where you define in a unit the interface and the implementation sections.要理解我们可以参考 Pascal 对象编码,您在一个单元中定义接口和实现部分。 In the interface you define the types and in the implementation you implement the type:在接口中定义类型,在实现中实现类型:

unit UnitName;

interface

type
  TheClass = class
  public
    procedure TheMethod;
  end;

implementation

class procedure TheClass.TheMethod;
begin
end;

Here, the interface section match to the UML class design while Interfaces types are thus others things.在这里,接口部分与 UML 类设计相匹配,而接口类型因此是其他东西。

So in our business we have one word, interface , to nominate two distinct but similar things, and it is a source of confusion.因此,在我们的业务中,我们有一个词interface来指定两个不同但相似的事物,这是混淆的根源。

Also in C# for example, programming interfaces allow to compensate the absence of true generic polymorphism on open types without really succeeding the goal because you lost the strongly-typed hability.同样在 C# 中,编程接口允许在没有真正实现目标的情况下补偿开放类型上真正的泛型多态性的缺失,因为你失去了强类型的 hability。

After all, interfaces are necessary to allow incompatible systems to communicate without worrying about the implementation and the management of objects in memory like introduced with the (Distributed) Common Object Model.毕竟,接口对于允许不兼容的系统进行通信而不必担心内存中对象的实现和管理是必要的,就像(分布式)公共对象模型引入的那样。

What is a class?什么是班级?

After defining a reduction of the reality from an external point of view, you can then describe it from an inside perspective: this is the class where you define data processing and message management to allow the reality you have encapsulated to come to life and interact thanks to objects using instances.在从外部的角度定义了现实的简化之后,您可以从内部的角度对其进行描述:这是您定义数据处理和消息管理以允许您封装的现实变得生动和交互的类,谢谢到使用实例的对象。

So in UML you realize a fractal immersion in the wheels of the machinery and you describe the states, the interactions and so on to be be able to implement the abstraction of the fragment of the reality you want to handle.因此,在 UML 中,您实现了机械轮子中的分形沉浸,并描述了状态、交互等,以便能够实现您想要处理的现实片段的抽象。

As such, an abstract class is somehow the equivalent of an interface from the point of view of the compiler.因此,从编译器的角度来看,抽象类在某种程度上相当于接口。

More information更多信息

Protocol (object-oriented programming) 协议(面向对象编程)

C# - Interfaces C# - 接口

C# - Classes C# - 类

You can only inherit from one abstract class.您只能从一个抽象类继承。 You can inherit from multiple interfaces.您可以从多个接口继承。 This determines what I use for most of the cases.这决定了我在大多数情况下使用什么。

The advantage of abstract class would be that you can have a base implementation.抽象类的优点是您可以拥有基本实现。 However, in the case of IDisposable, a default implementation is useless, since the base class does not know how to properly clean things up.然而,在 IDisposable 的情况下,默认实现是无用的,因为基类不知道如何正确清理。 Thus, an interface would be more suitable.因此,接口会更合适。

Both abstract class and interface are contracts.抽象类和接口都是契约。

The idea of a contract is you specify some behavior.契约的想法是你指定一些行为。 If you say you've implemented you've agreed to the contract.如果你说你已经实施了,你就同意了合同。

The choice of abstract over interrface is.抽象而不是接口的选择是。

Any non abstract descendant of the abstract class will implement the contract.抽象类的任何非抽象后代都将实现契约。

versus相对

Any class that implements the interface will implement the contract.任何实现接口的类都将实现契约。

So you use abstract when you want to specify some behavior all descendants must implement and save yourself defining a separate interface, but now everything that meets this effectively aggregated contract must be a descendant.因此,当您想要指定所有后代必须实现的某些行为并保存自己定义一个单独的接口时,您可以使用抽象,但现在满足此有效聚合契约的所有内容都必须是后代。

Let me tell you about flying toasters.让我告诉你飞行烤面包机。

飞行烤面包机

There are, of course, many situations where you can build a working software system without declaring or implementing any interfaces at all: any object-oriented software design can be realized using nothing but classes.当然,在很多情况下,您无需声明或实现任何接口就可以构建一个可工作的软件系统:任何面向对象的软件设计都可以仅使用类来实现。

Then again, any software system can also be implemented in Assembly Language, or better yet in Machine Code.再说一次,任何软件系统也可以用汇编语言实现,或者用机器代码更好。 The reason why we use abstraction mechanisms is because they tend to make things easier.我们使用抽象机制的原因是因为它们倾向于使事情变得更容易。 Interfaces are such an abstraction mechanism.接口就是这样一种抽象机制。

So, it just so happens that there are certain non-trivial object-oriented designs which are so much easier to implement if you use interfaces, that interfaces practically become necessary in those cases.因此,碰巧有某些非平凡的面向对象设计,如果您使用接口,它们将更容易实现,在这些情况下,接口实际上变得必要。

These non-trivial designs have to do with multiple inheritance, which, in its "true" form, is when a class inherits not from just one base class, but from two or more base classes.这些非平凡的设计与多重继承有关,在其“真实”形式中,一个类不仅从一个基类继承,而且从两个或多个基类继承。 This true form is not possible in C#, but before languages like C# and Java came into existence, the language that ruled was C++, which fully supports true multiple inheritance.这种真实的形式在 C# 中是不可能的,但是在 C# 和 Java 等语言出现之前,统治的语言是 C++,它完全支持真正的多重继承。 Unfortunately, true multiple inheritance turned out to not be a very good idea, because it immensely complicates the design of the language, and it also gives rise to various problems, for example the famous "Diamond Problem".不幸的是,真正的多重继承被证明不是一个很好的主意,因为它极大地使语言的设计复杂化,并且还会引发各种问题,例如著名的“钻石问题”。 (See "What is the exact problem with multiple inheritance?" answer by J Francis ) (参见“多重继承的确切问题是什么?”J Francis 的回答

So, if someone wanted to build a "flying toaster" class, they would inherit from some existing "toaster" class and also from some existing "flying" class.因此,如果有人想要构建一个“飞行烤面包机”类,他们将继承一些现有的“烤面包机”类以及一些现有的“飞行”类。 The kind of problem they were likely to run into was that the power supply of the toaster class was likely to be a wall socket, while the power supply of the flying machine class was likely to be pigeon food, and the resulting new class would either somehow have both, or it would be unclear which one it would have.他们可能遇到的问题是烤面包机类的电源很可能是墙上的插座,而飞行器类的电源很可能是鸽子食,由此产生的新类要么不知何故两者都有,或者不清楚它会有哪一个。 (The Diamond Problem.) (钻石问题。)

The creators of languages like C# and Java decided to not allow true multiple inheritance, in order to keep the language simple and to avoid pitfalls like the Diamond Problem. C# 和 Java 等语言的创建者决定不允许真正的多重继承,以保持语言简单并避免钻石问题等陷阱。 However, some form of multiple inheritance is still necessary, (or at least very highly desirable,) so in these languages they introduced interfaces as a means of supporting a lesser form of multiple inheritance while avoiding the problems and the complexity of true multiple inheritance.然而,某种形式的多重继承仍然是必要的(或者至少非常需要),因此在这些语言中,他们引入了接口作为支持较少形式的多重继承的一种手段,同时避免了真正多重继承的问题和复杂性。

In this lesser form of multiple inheritance, you are not allowed to have a class which inherits from more than one base class, but you can at least inherit from one or more interfaces.在这种较少形式的多重继承中,不允许一个类从多个基类继承,但至少可以从一个或多个接口继承。 So, if you want to build a flying toaster, you cannot inherit both from some existing toaster class and some existing flying class, but what you can do is inherit from an existing toaster class and then also expose a flying interface which you implement yourself, possibly using whatever means you have already inherited from toaster.所以,如果你想构建一个飞行烤面包机,你不能同时继承一些现有的烤面包机类和一些现有的飞行类,但你可以做的是从现有的烤面包机类继承,然后公开一个你自己实现的飞行接口,可能使用您已经从烤面包机继承的任何方式。

So, unless you ever feel the need to create a class which aggregates two different and unrelated sets of functionality, you are not going to need any form of multiple inheritance, so you are not going to need to declare, or implement, any interfaces.因此,除非您觉得需要创建一个聚合两个不同且不相关的功能集的类,否则您不需要任何形式的多重继承,因此您不需要声明或实现任何接口。

Interfaces allow the class designer to make the available methods very clear for the end user.接口允许类设计者为最终用户提供非常清晰的可用方法。 They are also an integral part of polymorphism.它们也是多态性的组成部分。

I won't post the definition of an interface against an abstract class because I think you know very well the theory and I assume you know the SOLID principles so let's get practical.我不会针对抽象类发布接口的定义,因为我认为您非常了解理论,并且我假设您了解 SOLID 原则,所以让我们开始实践。

As you know interfaces cannot have any code so the dis-vantage are quite simple to understand.如您所知,接口不能有任何代码,因此缺点很容易理解。

if you need to initialize the property of your class providing a constructor or you want to provide part of the implementation an abstract class would be a good fit against an interface which would not allow you to do that.如果您需要初始化提供构造函数的类的属性,或者您想提供实现的一部分,则抽象类将非常适合不允许您这样做的接口。

So in very general you should prefer abstract class to interfaces when you need to provide a constructor or any code to the client which will inherit/extend your class因此,一般而言,当您需要向将继承/扩展您的类的客户端提供构造函数或任何代码时,您应该更喜欢抽象类而不是接口

Abstract class are crated for related entities where as Interfaces can be used for unrelated entities.抽象类是为相关实体创建的,而接口可用于不相关的实体。

For eg if I have two entities say Animal and Human then i will go for Interface where as if i have to go in detail say Tiger,lion and want to relate with Animal then will choose Animal Abstract class..例如,如果我有两个实体,比如 Animal 和 Human,那么我会选择 Interface,好像我必须详细说 Tiger,lion 并且想要与 Animal 联系,然后会选择 Animal Abstract 类。

will look like below看起来像下面

   Interface             
   ____|____
  |        |
Animal   Human



  Animal (Abstract class)
   __|___
  |      |
Tiger   Lion

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用扩展方法来实现接口吗? - Can I use Extension Methods to implement an Interface? C# - 我应该使用什么,接口,抽象类或两者? - C# - What should I use, an Interface, Abstract class, or Both? 在.NET中如何在没有接口继承的情况下在静态类中实现接口方法? - How can I implement interface methods in the static class without Interface Inheritance in .NET? 类何时应实现接口,何时不应实现接口? - When Should a Class Implement an Interface, and When Should it Not? 我如何使用:Interface实现类? - How can i implement a class using :Interface? 在这种情况下应该使用接口还是抽象类? - Should I use an interface or abstract class in this scenario? 接口继承-从父接口隐藏方法-为什么在实现类中可以同时使用这两种方法? - Interface inheritance - hiding method from parent interface - why can I have both methods in the implementing class? 我的类应该实现哪种接口或方法以在Console.WriteLine中打印我想要的内容? - What interface or method should my class implement to print what I want in Console.WriteLine? 再次在界面中构造; 为什么我可以像上课一样使用它? - Struct in interface again; Why can I use it like class? 从接口继承时如何使用派生类 - How can I use derived class when inherite from an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM