【发布时间】:2017-02-03 13:35:52
【问题描述】:
我必须编写一个名为 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
{
...
}
之后,我写了一个接口:
// IVehicleRepository.cs
public interface IVehicleRepository
{
void Add(Vehicle item);
IEnumerable<Vehicle> GetAll();
Vehicle Find(string key);
Vehicle Remove(string key);
void Update(Vehicle item);
}
所以我想我可以使用这样的东西:
// 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
}
但是,我遇到了错误:
错误 CS0738:“CarRepository”未实现接口成员“IVehicleRepository.GetAll()”。 'CarRepository.GetAll()' 无法实现 'IVehicleRepository.GetAll()' 因为它没有匹配的返回类型 'IEnumerable'。
那么,我该怎么做呢?
【问题讨论】:
标签: c# interface polymorphism abstract