可能的重复:
接口与抽象类(一般 OO)
我可以看到他们在协调开发团队或可能由其他人进一步开发的代码方面的优势。
但如果没有,是否有理由使用它们?如果我省略它们会发生什么?
摘要——我将能够实例化它。没问题。如果这没有意义——我不会。
接口——无论如何,我在派生它的所有类中都声明了该功能。
注意:我不是在问它们是什么。我在问他们是否对协调以外的任何事情都有帮助。
可能的重复:
接口与抽象类(一般 OO)
我可以看到他们在协调开发团队或可能由其他人进一步开发的代码方面的优势。
但如果没有,是否有理由使用它们?如果我省略它们会发生什么?
摘要——我将能够实例化它。没问题。如果这没有意义——我不会。
接口——无论如何,我在派生它的所有类中都声明了该功能。
注意:我不是在问它们是什么。我在问他们是否对协调以外的任何事情都有帮助。
Both are what I call contracts and can be used in the following fashion by an individual developer:
Abstract
Interface
contract of operation(s).
This usage is can be targetted to the process in hand and allows for the
surgically precise operations for that contract. Long story short are they required to get a job done? No.
But if you are into designing systems which will have a lifespan of more than one cycle, the upfront work by said architect will pay off in the long run whether on a team or by an individual.
++Update
I do practice what I preach and when handing off a project to other developers it was nice to say
IProcess which all the primary business classes adhere to. That process defines a system of goals which can help you understand the purpose and the execution of the business logic in a defined way.抽象 - 你可以实例化它的一个孩子,但更重要的是,它可以有自己的非抽象方法和字段。
接口 - 就抽象而言更“粗略”的一种,但.NET您可以拥有多重继承。因此,通过定义接口,您可以引导接口的使用者订阅不同的合约(接口),从而呈现指定类型的不同“形状”。
我认为如果你不与他人协调,它会做两件事
即使您没有与任何人协调,也有很多理由使用这两种结构。主要用途是两者实际上都有助于表达开发者的意图,这可能会帮助您稍后弄清楚为什么选择您实际选择的设计。它们还可以允许进一步的可扩展性。
抽象类允许您定义一个通用实现,该实现将在许多派生类之间共享,同时将一些行为委托给子类。它允许 DRY(不要重复自己)原则,以避免在任何地方重复相同的代码。
接口表示你的类实现了一个特定的契约。这在框架内有一个非常有用的用途,其中:
使用需要实现某些接口的库功能。示例是 IDisposable、IEquatable、IEnumerable...
在泛型中使用约束。
允许模拟接口(如果您进行单元测试)而不必实例化真实对象。
COM 对象的使用