繁体   English   中英

与抽象类的接口

[英]Interface with abstract class

我必须编写一个名为Vehicle的类,它具有许多属性(例如,尺寸,座位,颜色等),还有两个要编写的类,它们具有自己的属性,即TrunkCar

所以我写了:

// Vehicle.cs
abstract public class Vehicle
{
    public string Key { get; set; }
    ...
}

// Car.cs
public class Car : Vehicle
{
    ...
}

// Trunk.cs
public class Trunk : Vehicle
{
    ...
}

之后,我编写了一个Interface:

// 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 <'Vehicle>'。

那么,我该怎么做呢?

您的CarRepository没有实现该方法。 这两个不一样:

  • public IEnumerable<Car> GetAll()
  • IEnumerable<Vehicle> GetAll()

这是两种不同的类型,当您从接口派生时,必须完全实现它。 您可以通过以下方式实现它:

public IEnumerable<Vehicle> GetAll()
{
    // Cast your car collection into a collection of vehicles
}

但是,更好的方法是使其成为以下类的通用接口:(缺点是两个不同的实现类型又是两个不同的类型,因此请查看是否是您想要的)

public interface IVehicleRepository<TVehicle> {}
public class CarRepository : IVehicleRepository<Car> {}

一个更完整的版本:

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;
    }
}

您可以使IVehicleRepository通用:

public interface IVehicleRepository<T> where T : Vehicle
{
    void Add(T item);
    IEnumerable<T> GetAll();
    Vehicle Find(string key);
    Vehicle Remove(string key);
    void Update(T 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;
    }
}

但是您仍然会CarRepository以下问题: CarRepositoryIVehicleRepository<Car>TruckRepositoryIVehicleRepository<Truck> 并且这两个接口是不同的类型,并且只有在具有正确的方差时才可以彼此分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM