封装,继承,多态,接口的使用
父类—交通工具
public abstract class Vehicle
{
public string VehicleName { get; set; }
private int peopleLoad;
public int PeopleLoad
{
get { return peopleLoad; }
set
{
if (value <0 || value >50)
{
throw (new ArgumentOutOfRangeException("CarryPeople", value, "载客人数应在0-50之间"));
}
peopleLoad = value;
}
}
public Vehicle() { }
public Vehicle (string vehicleName,int peopleLoad)
{
this.PeopleLoad = peopleLoad;
this.VehicleName = vehicleName;
}
public void CarryPeople()
{
Console.WriteLine(VehicleName + "可以承载" + peopleLoad + "人!");
}
public virtual void EnergySources()
{
Console.WriteLine(VehicleName + "使用什么能源?");
}
}
子类—公交车
public class Bus:Vehicle ,IReful
{
public override void EnergySources()
{
base.EnergySources();
Console.WriteLine(VehicleName + "使用92#汽油!");
}
public void Reful()
{
Console.WriteLine(VehicleName + "是运营车辆");
}
}
子类-----电动车
public class Electrocar:Vehicle
{
public override void EnergySources()
{
base.EnergySources();
Console.WriteLine(VehicleName + "使用充电桩补充能源");
}
public Electrocar(string vehicleName, int peopleLoad)
{
this.VehicleName = vehicleName;
this.PeopleLoad = peopleLoad;
}
}
接口—运营
interface IReful
{
void Reful();
}
使用
class Program
{
static void Main(string[] args)
{
Bus bus = new Bus();
bus.VehicleName = "公交车";
bus.PeopleLoad = 46;
bus.CarryPeople();
bus.EnergySources();
bus.Reful();
Console.WriteLine("---------------------------------------");
Taxi taxi = new Taxi("出租车", 5);
taxi.CarryPeople();
taxi.EnergySources();
taxi.Reful();
Console.WriteLine("---------------------------------------");
Electrocar electrocar = new Electrocar("电动汽车", 5);
electrocar.CarryPeople();
electrocar.EnergySources();
Console.ReadLine();
}
}
运行结果
公交车可以承载46人!
公交车使用什么能源?
公交车使用92#汽油!
公交车是运营车辆
---------------------------------------
出租车可以承载5人!
出租车使用什么能源?
出租车使用95#汽油
出租车是运营车辆
---------------------------------------
电动汽车可以承载5人!
电动汽车使用什么能源?
电动汽车使用充电桩补充能源