Interfaces vs. abstract classes

This question already has an answer here:

  • When should I choose inheritance over an interface when designing C# class libraries? 6 answers
  • Interface vs Base class 39 answers

  • The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"
  • Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.


    Abstract classes and interfaces are semantically different, although their usage can overlap.

    An abstract class is generally used as a building basis for similar classes. Implementation that is common for the classes can be in the abstract class.

    An interface is generally used to specify an ability for classes, where the classes doesn't have to be very similar.


    另一件需要考虑的事情是,由于没有多重继承,如果你希望一个类能够实现/从你的接口/抽象类继承,但是从另一个基类继承,那就使用一个接口。

    链接地址: http://www.djcxy.com/p/38140.html

    上一篇: 你如何决定使用抽象类和接口?

    下一篇: 接口与抽象类