如何确定何时应使用接口以及何时应使用抽象类 [英] How to identify when should I use Interface and when should I use abstract class

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

问题描述

据我所知,以下是确定规则

接口:这是接口和实现的类之间的契约.接口定义协议,该协议强调已实现的类将如何行为和通信.

抽象类:有助于巩固所有扩展类的通用功能.

According to my knowledge following are the determination rules

Interface: It’s a contract between interface and implemented class. Interface defines the protocol which emphasis how implemented classes will behave and communicate. It simplifies design complexity and brings more consistency in code writing.

Abstract Class: It helps to consolidate common functionality of all extended class.

 任何人也可以分享他们的想法.

 Can anybody share their idea too.

推荐答案

这些是我认为要点:

These are what I consider to be the main points:

如果使用interface,则实现它的所有对象都必须提供自己的接口规范实现.

If you use an interface, all objects that implement it will have to provide their own implementations of your interface specification.

如果使用abstract class,则可以提供基本实现,因此派生类不需要具有自己的实现.或者,您可以将属性/方法标记为虚拟,以便派生类可以选择提供自己的功能或将其标记为抽象,以便它们必须提供自己的实现.仅具有抽象方法和属性的抽象类的行为与接口大致相同.

If you use an abstract class, then you can provide a base implementation so the derived classes do not need to have their own implementation. Alternatively you can mark properties/methods as virtual so that deriving classes can optionally provide their own implentation or mark them as abstract so they must provide their own implementation. An abstract class with only abstract methods and properties behaves much the same as an interface.

一个对象可以直接实现许多接口,但只能实现一个抽象类(C#中没有多重继承).

An object can implement many interfaces directly but only one abstract class (no multiple inheritance in C#).

结构只能实现接口,不能实现抽象类.

Structs can only implement interfaces and not abstract classes.


我愿意尝试一下.

Well, I''m willing to have a try.

接口是完整的定义,但没有代码.实现接口时,必须提供相关代码的实现.

An interface is a complete definition but without the code. When you implement the interface you must provide the implementation of the relevant code.

抽象类是可用于创建相关类的基础类.将动物视为抽象的基础,将猫,狗,猴子等作为相关类.

An abstract class is a base class that can be built upon to create related classes. Think animal as an abstract base, with cat, dog, monkey etc. as related classes.


这不是通用答案,而是两种机械"决定方式:

This isn''t a universal answer but two "mechanical" ways to decide:

如果该类具有任何数据,则它必须是Abstract类...接口可能不包含数据.

If the class has any data, it must be an Abstract class...Interfaces may not include data.

可以将接口添加到已经从另一个类派生的类中.它是多重继承的一种形式.如果需要向现有类添加行为,则需要一个接口.

An Interface can be added to a class that has already been derived from another class.  It is a form of multiple inheritance.  If you need to add behavior to existing classes, you''ll need an Interface.


这篇关于如何确定何时应使用接口以及何时应使用抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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