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

时间:2018-12-06 10:03:16

标签: c# oop collections interface ienumerable

如果我的接口带有返回某物集合的方法,是否有可能返回该集合类型的实现?

例如:

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

如果没有,为什么不呢?

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

2 个答案:

答案 0 :(得分:5)

您当然可以自由返回IEnumerable<Part>的任何实现,作为GetParts方法的实现细节(例如,Train可以轻松返回List<Part>)。但是方法签名必须在接口定义和该方法的类的实现之间精确地匹配。

此处(与重载不同)方法签名包含方法的返回类型。因此,不能,您不能像显示的那样写Car或类似内容。您当然可以自由使用GetParts方法,该方法确实返回List<Part>,但不满足接口要求-您可以选择为其提供显式实现:

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

答案 1 :(得分:1)

否,C#不支持继承方法的返回类型的协方差。

Does C# support return type covariance?