我最近问过这个question关于我应该实现接口(interface)还是抽象类。 Scottm 给出的答案建议我同时使用两者,但我仍然不确定我为什么要这样做。从长远来看有好处吗?这样做有什么好处?
以下是我认为的一些好处:
这是另一个问题。如果我实现一个接口(interface),该接口(interface)应该只包含所有子类都可以做的方法吗?如果我需要额外的逻辑,我会创建一个具有更具体实现的具体类或抽象类。
最佳答案
这种方法为您提供了两全其美的优势 - 接口(interface)的灵 active 和基类的有用选项。
通过只要求消费者实现您的接口(interface),您不会强制他们失去对其类开放的唯一继承槽(C# 不允许多重继承)。
但是通过另外提供一个抽象基类,你可以给他们一个“腿”,也许通过实现一些可能是大多数接口(interface)实现的共同要求的帮助功能 - 例如这可以使用模板方法来实现图案。
在 .NET Framework 本身中有几个公开接口(interface)和基类的示例。例如 System.ComponentModel.IComponent
和 System.ComponentModel.Component
Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do?
是的。您实际上是在描述 Interface Segregation Principle .
关于.net - 让抽象类实现接口(interface)的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7599744/