C# 接口与抽象类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/747517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:37:19  来源:igfitidea点击:

Interfaces vs. abstract classes

c#inheritanceinterfaceabstract-class

提问by tush1r

In C#, when should you use interfaces and when should you use abstract classes? What can be the deciding factor?

在 C# 中,什么时候应该使用接口,什么时候应该使用抽象类?什么是决定因素?

采纳答案by JaredPar

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.

接口只是数据传递合约,不具备这些特性。但是,它们通常更灵活,因为一种类型只能从一个类派生,但可以实现任意数量的接口。

回答by Dave Van den Eynde

The real question is: whether to use interfaces or base classes. This has been covered before.

真正的问题是:是使用接口还是基类。这在前面已经介绍过了。

In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

在 C# 中,抽象类(用关键字“abstract”标记的类)只是一个不能从中实例化对象的类。这与简单地区分基类和接口的目的不同。

回答by Guffa

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.

接口通常用于指定类的能力,其中类不必非常相似。

回答by Zifre

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

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