.net - 让抽象类实现接口(interface)的好处?

标签 .net oop inheritance interface abstract-class

我最近问过这个question关于我应该实现接口(interface)还是抽象类。 Scottm 给出的答案建议我同时使用两者,但我仍然不确定我为什么要这样做。从长远来看有好处吗?这样做有什么好处?

以下是我认为的一些好处:

  • 我可以在不破坏实现的情况下向抽象类添加方法,但是使用接口(interface),我会破坏它。
  • 我可以继承多个接口(interface),但只能继承一个抽象类
  • 抽象类允许我定义标准行为,但如果我愿意,可以覆盖它。

  • 这是另一个问题。如果我实现一个接口(interface),该接口(interface)应该只包含所有子类都可以做的方法吗?如果我需要额外的逻辑,我会创建一个具有更具体实现的具体类或抽象类。

    最佳答案

    这种方法为您提供了两全其美的优势 - 接口(interface)的灵 active 和基类的有用选项。

    通过只要求消费者实现您的接口(interface),您不会强制他们失去对其类开放的唯一继承槽(C# 不允许多重继承)。

    但是通过另外提供一个抽象基类,你可以给他们一个“腿”,也许通过实现一些可能是大多数接口(interface)实现的共同要求的帮助功能 - 例如这可以使用模板方法来实现图案。

    在 .NET Framework 本身中有几个公开接口(interface)和基类的示​​例。例如 System.ComponentModel.IComponentSystem.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/

    相关文章:

    c# - 使用项目程序集信息的 log4net 文件路径

    c# - 我们必须使用接口(interface)的真实示例......而不是抽象类......写一些代码

    c# - 为什么我应该用泛型替换 CollectionBase?

    javascript - "the remote procedure call failed"- 仅限 IE

    swift - Swift 中的 Getters 和 Setters - 改用 WillSet 和 DidSet 是否有意义?

    c++ - 具有附加默认参数的接口(interface)实现?

    java - 如何跟踪/记录实体变更的版本

    python - 通过多个类进行类继承

    xml - log4j 可以从基本/根元素继承 xml 吗?

    c#-4.0 - 不包含带有 0 个参数的构造函数