将集合类型从接口更改为实现 class

Changing Collection type from Interface to Implementing class

如果我有一个接口,其方法 return 是某物的集合,是否可以 return 集合类型的实现来代替?

例如:

public interface IVehicle
{
    IEnumerable<Part> GetParts(int id);
}

public class Car : IVehicle
{
    List<Part> GetParts(int id)
    {
        //return list of car parts
    }
}

public class Train : IVehicle
{
    IEnumerable<Part> GetParts(int id)
    {
        //return IEnumerable of train parts
    }
}

如果不是,为什么不呢?

至少对我来说,这是有道理的。

您当然可以 return IEnumerable<Part> 的任何实现作为您的 GetParts 方法的实现细节(例如 Train 可以 return List<Part> 很容易)。但是方法签名必须 完全匹配 接口定义和 class 该方法的实现。

此处(与重载不同)方法签名包括方法的 return 类型。所以不,你不能写 Car 如图所示或类似的东西。您当然可以自由使用 执行 return 和 List<Part>GetParts 方法,但这不能满足接口要求 - 您可以选择为替代提供明确的实现:

public class Car : IVehicle
{
    List<Part> GetParts(int id)
    {
        //return list of car parts
    }
    IEnumerable<Part> IVehicle.GetParts(int id) => this.GetParts(id);
}

不,C# 不支持继承方法 return 类型的协变。

Does C# support return type covariance?