C#中的继承 [英] Inheritence in C#

查看:92
本文介绍了C#中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,

我根据以下内容对我的班级提出设计建议。

I have a design advise on my classes based on the follwoing.

假设我有一个主要的class wish是Car()

然后我有继承Car()的子类,可以是Mercedes(),Ferari,Chevrelet()

然后我可以拥有使用燃料或电能的汽车

Let say I have a main class wish is a Car()
Then I have sub class which inherit from Car() which can be Mercedes(), Ferari, Chevrelet()
Then I can have Cars which are using fuel or electric energie

基于此,我应该创建新的Class Energy(),然后将子类继承为Fuel()和Energy(),或者我应该更好在特定的Car类中创建那些类?

Based on that should I create new Class Energy(), then sub class inherited from it as Fuel() and Energy(), or should I better create those class inside a particular class of Car ?

实际上我试图确定的主要观点是,在我们认为类结构开始变得复杂并需要多少类层次之后简化?

In fact the main point I try to identify is that after how many class hierarchy should we consider the class structure start to be complicated and need to be simplified ?

感谢您的建议

问候

推荐答案

继承是指当某个对象显然是另一个对象的子类型时,它具有的属性和功能。

Inheritance is for when some object is clearly a sub-type of another object in terms the properties and functionality that it has.

所以法拉利是一种类型的汽车,因为法拉利有al l与任何汽车(方向盘,车轮,底盘等)相同的基本属性,并执行相同的功能(通过轮式运动提供从一个位置到另一个位置的运输)。加上
它还具有特定于法拉利的附加功能。

So a Ferrari is a type of Car, because a Ferrari has all the same basic properties of any car (steering wheel, wheels, a chassis etc) and performs the same function (provides transportation from one location to another by way of wheeled locomotion). Plus it has additional features specific to a Ferrari.

但是"电动"不是一种面向对象意义上的汽车(尽管我们倾向于说它的语言)。它本身没有 - 具有相同的属性:'电'没有轮子。你无法驾驶"电动"工作。实际上,电动汽车的价格为b $ b,可以适用于各种特定类型的汽车,如梅赛德斯,法拉利等。

But an 'electric' is not a type of car in an object-oriented sense (despite the way we tend to say it language). It does not - on its own - have the same properties: An 'electric' does not have wheels. You cannot drive an 'electric' to work. The property of being of electric in fact could apply across a number of specific types of car across the board such as Mercedes, Ferraris etc.

相反,一辆汽车有房产代表燃料的类型,可以是汽油,柴油,电动,混合动力,氢燃料电池等。

Instead, A car has a property representing the type of fuel which can be Petrol, Diesel, Electric, Hybrid, Hydrogen fuel-cell etc.

总结:我会说,如果我有一个汽车类,我也会定义一个类型FuelSource的枚举。然后,汽车类可以具有FuelSource类型的属性,该属性将定义其使用的燃料类型。所有来自Car的类(如法拉利)都会
继承该属性。 (可能存在其他解决方案!)。

Summary: I would say that if I had a Car class, I would also define an enum of type FuelSource. The car class could then have a property of type FuelSource that would define the type of fuel it uses. All classes that derive from Car (such as Ferrari) would inherit that property. (Other solutions may exist!).

例如

enum FuelSource {Petrol, Diesel, Electric};

public class Car
{
   property FuelSource FuelType{get;set;}
}

public class Ferrari: Car
{
}


这篇关于C#中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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