简体   繁体   English

oop接口,继承,基类,

[英]oop interface, inheritance, base class,

I'm trying to learn interface and base classes on practical example. 我正在尝试在实际示例中学习接口和基类。 Let's say that I want to to abstract Player entity On Player.cs should be all common properties and methods for every sport in which player is assigned. 让我们说我想要抽象玩家实体在玩家。应该是所有玩家被分配的运动的常见属性和方法。 So, there will be TeamSportPlayer, IndividualSportPlayer. 因此,将有TeamSportPlayer,IndividualSportPlayer。 Again, FootballPlayer would derive from TeamSportPlayer, TennisPlayer would derive from IndividualSportPlayer and so on. 同样,FootballPlayer将派生自TeamSportPlayer,TennisPlayer将派生自IndividualSportPlayer等。 All this players should have access to first class Player and their properties. 所有这些球员都应该能够获得一流的球员及其属性。

Hope I'm not too confusing. 希望我不要太困惑。

Question is: Is this proper way of abstracting player representation in terms of oop? 问题是:这是以oop方式抽象玩家代表的正确方法吗?

How would you do this on this practical example? 你会如何在这个实际例子中做到这一点?

Abstract classes are used for defining objects that you are never going to have an instance of. 抽象类用于定义您永远不会拥有实例的对象。 Interfaces on the other hand are used to define behaviour of objects, and interfaces are independent from the inheritance hierarchy. 另一方面,接口用于定义对象的行为,接口独立于继承层次结构。

Using your sports example: 使用您的体育示例:

Player.cs can be an abstract class. Player.cs可以是一个抽象类。 It has fields that every player has like name, age, address, etc. But you never have a "Player" on the sports field, you have a "Football player" or a "Basketball player". 它有每个球员都有的名字,年龄,地址等字段。但你从来没有在运动场上有“球员”,你有一个“足球运动员”或“篮球运动员”。 And the classes FootballPlayer.cs and BasketballPlayer.cs inherit from the abstract class Player.cs. FootballPlayer.csBasketballPlayer.cs类继承自抽象类Player.cs。

Interface on the other hand defines some common behaviour that the classes share. 另一方面,接口定义了类共享的一些常见行为。 Usually its used to define how other classes can interact with them. 通常用于定义其他类如何与它们交互。 So for instance, if you have classes called TennisPlayer.cs , BasketballPlayer.cs and FootballPlayer.cs you can have an interface called IHasJerseyNumber.cs . 因此,例如,如果你有名为TennisPlayer.csBasketballPlayer.csFootballPlayer.cs类,你可以拥有一个名为IHasJerseyNumber.cs的接口。 Basketball and football players have jersey numbers so they would inherit the IHasJerseyNumber.cs interface. 篮球和足球运动员都有球衣号码,所以他们会继承IHasJerseyNumber.cs界面。 Tennis players don't have a number and they wont inherit the interface. 网球运动员没有号码,他们不会继承界面。 A totally seperate class like Referee.cs can implement the interface as well, providing he too has a jersey number (possible in some sports). Referee.cs这样的完全独立的类也可以实现界面,只要他也有一个球衣号码(在某些运动中可能)。

You can read more here: 你可以在这里阅读更多:

Interfaces 接口

Abstract classes 抽象类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM