1 c# polymorphism interface abstract
我必须编写一个Vehicle带有许多属性(例如大小,座位,颜色......)的类,并且我还有两个要编写的类Trunk和Car它们自己的属性.
所以我写了:
// Vehicle.cs
abstract public class Vehicle
{
public string Key { get; set; }
...
}
// Car.cs
public class Car : Vehicle
{
...
}
// Trunk.cs
public class Trunk : Vehicle
{
...
}
Run Code Online (Sandbox Code Playgroud)
之后,我写了一个接口:
// IVehicleRepository.cs
public interface IVehicleRepository
{
void Add(Vehicle item);
IEnumerable<Vehicle> GetAll();
Vehicle Find(string key);
Vehicle Remove(string key);
void Update(Vehicle item);
}
Run Code Online (Sandbox Code Playgroud)
所以我在想我可以使用这样的东西:
// CarRepository.cs
public class CarRepository : IVehicleRepository
{
private static ConcurrentDictionary<string, Car> _cars =
new ConcurrentDictionary<string, Car>();
public CarRepository()
{
Add(new Car { seats = 5 });
}
public IEnumerable<Car> GetAll()
{
return _cars.Values;
}
// ... I implemented the other methods here
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了错误:
错误CS0738:'CarRepository'未实现接口成员'IVehicleRepository.GetAll()'.'CarRepository.GetAll()'无法实现'IVehicleRepository.GetAll()',因为它没有匹配的返回类型'IEnumerable <'Vehicle>'.
那么,我该怎么做呢?
您CarRepository没有实施该方法.这两个不一样:
public IEnumerable<Car> GetAll()IEnumerable<Vehicle> GetAll()这些是两种不同的类型,当您从界面派生时,您必须完全实现它.你可以这样实现它:
public IEnumerable<Vehicle> GetAll()
{
// Cast your car collection into a collection of vehicles
}
Run Code Online (Sandbox Code Playgroud)
然而,更好的方法是使它成为通用接口:(缺点是两个不同的实现类型再次是两种不同的类型,所以看看这是否是你想要的)
public interface IVehicleRepository<TVehicle> {}
public class CarRepository : IVehicleRepository<Car> {}
Run Code Online (Sandbox Code Playgroud)
更完整的版本:
public interface IVehicleRepository<TVehicle> where TVehicle : Vehicle
{
void Add(TVehicle item);
IEnumerable<TVehicle> GetAll();
Vehicle Find(string key);
Vehicle Remove(string key);
void Update(TVehicle item);
}
public class CarRepository : IVehicleRepository<Car>
{
private static ConcurrentDictionary<string, Car> _cars =
new ConcurrentDictionary<string, Car>();
public CarRepository()
{
Add(new Car { seats = 5 });
}
public IEnumerable<Car> GetAll()
{
return _cars.Values;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |