C#抽象类 [英] c# abstract classes
问题描述
我要创建一个计算年费,商业和私人车辆假DMV程序。这两个类将是抽象的,他们会从一个叫所有车辆类多态。
i have to create a fake DMV program that calculates annual fees, for commercial and private vehicles. Those two classes will be abstract and they will polymophism from a class named all vehicles.
我的教练希望只有一个对象创建的整个程序(主),但因为我的顶级3层类是抽象的。我无法和他们创建一个对象,即车辆=新车();
My instructor wants only one object created the entire program(in main) but since my top 3 tier classes are abstract. I can't create an object with them i.e. vehicles = new vehicles();
所以我的问题是我如何创建只有一个对象,因为它们是抽象的?如果您有任何问题随时问,我可能没有解释这口井......
so my question is how do i create only one object since they are abstract? If you have any questions feel free to ask, I might have not explained this well...
推荐答案
您的阶级结构会看是这样的:
Your class structure will look something like:
abstract class Vehicle
{
protected abstract int BaseFee { get; }
protected abstract int ExtraFee { get; }
public int CalculateFee()
{
return BaseFee + ExtraFee;
}
}
abstract class CommercialVehicle : Vehicle
{
protected override int BaseFee
{
return 100;
}
}
class LightDutyTruck : CommercialVehicle
{
protected override int ExtraFee
{
return 50;
}
}
class Semi : CommercialVehicle
{
protected override int ExtraFee
{
return 150;
}
}
[etc...]
abstract class PrivateVehicle : Vehicle
{
protected override int BaseFee
{
return 25;
}
}
class Sedan : PrivateVehicle
{
protected override int ExtraFee
{
return 15;
}
}
和等,为每个类。在你的主
方法,你会根据输入创建实例,但你的实际变量将被声明为类型车
。实际计算将根据您创建实例生效:
and so on, for each class. In your Main
method, you would create the instance based on input, but your actual variable would be declared as type Vehicle
. The actual calculation will take effect based on the instance that you create:
Vehicle v;
switch(input)
{
case "semi":
v = new Semi();
break;
case "truck":
v = new LightDutyTruck();
break;
...
}
int fee = v.CalculateFee();
这篇关于C#抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!