有人可以解释C#中接口的确切用法吗?
问题描述:
有人可以解释C#中接口的确切用法吗?
Can someone explain the exact use of interfaces in C#?
答
想象一下创建汽车的工厂的情况。你知道每辆车都有一个引擎,可以启动,所以你有以下几点:
Imagine the the situation of having a factory that creates cars. You know that every vehicle has an engine and can be started, so you have the following:
interface IVehicle
{
Engine vehicleEngine { get; set; }
bool StartEngine();
}
现在,工厂制造了一系列其他车辆,例如一辆卡车和普通汽车:
Now, the factory makes an array of other vehicles, so for instance a truck and a normal car:
public Car : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Cars needs to do xyz to start
}
public int MaxNumberOfPassenger { get; set; } // Specific to Car
}
然后:
public Truck : IVehicle
{
// MUST implement vehicleEngine and StartEngine:
public Engine vehicleEngine { get; set; }
public bool StartEngine()
{
// Trucks needs to do abc to start
}
public int MaximumLoad { get; set; } // Specific to Truck
}
因此,这迫使所有车辆实施特定会员属于车辆类别,但也可以专门与他们自己的独特成员。
This therefore forces all vehicles to implement specific members to fall under the category of a vehicle, but then can also be specialized with their own distinct members.