接口与抽象类 [英] Interfaces vs. abstract classes

查看:25
本文介绍了接口与抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

更新:C# 8.0 新功能:从 C# 8.0 开始,接口可以为成员定义默认实现,包括属性.很少为接口中的属性定义默认实现,因为接口可能不会定义实例数据字段.

Update: C# 8.0 New Feature: Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

抽象类的优点是:

  • 能够指定方法的默认实现
  • 为函数添加了不变性检查
  • 对界面"的方式有更多的控制.方法被称为
  • 能够免费"提供与界面相关或无关的行为

接口只是数据传递契约,没有这些特性.然而,它们通常更灵活,因为一种类型只能从一个类派生,但可以实现任意数量的接口.

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.

这篇关于接口与抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆