首页 > 解决方案 > 将派生类传递给使用父类c#的方法

问题描述

今天我参加了测试,将静态方法 getMovingVehicles 添加到已经编写的代码中。我按照您在下面看到的那样进行了操作,但是在通过在线编译器传递之后,我可以看到出现如下错误:

Compilation error (line 28, col 39): The best overloaded method match for 'Rextester.Program.getMovingVehicles(System.Collections.Generic.List<Rextester.Vehicle>)' has some invalid arguments
Compilation error (line 28, col 57): Argument 1: cannot convert from 'System.Collections.Generic.List<Rextester.Car>' to 'System.Collections.Generic.List<Rextester.Vehicle>'
Compilation error (line 29, col 41): The best overloaded method match for 'Rextester.Program.getMovingVehicles(System.Collections.Generic.List<Rextester.Vehicle>)' has some invalid arguments
Compilation error (line 29, col 59): Argument 1: cannot convert from 'System.Collections.Generic.List<Rextester.Plane>' to 'System.Collections.Generic.List<Rextester.Vehicle>'

我应该如何将派生类传递给使用父类使其正常工作的方法?

namespace Rextester
{
 abstract class Vehicle{
    public int Speed; 
    }

     class Car: Vehicle{
     public String VIN;   
    }

     class Plane : Vehicle{
     public int altitude;   
    }

public class Program
{


    public static void Main(string[] args)
    {

        var cars= new List<Car>();
        var planes = new List<Plane>();
        List<Vehicle> movingCars= getMovingVehicles(cars);
        List<Vehicle> movingPlanes=getMovingVehicles(planes);

    }

     static List<Vehicle> getMovingVehicles(List<Vehicle> vehicles){
        List<Vehicle> movingVehicles=new List<Vehicle>();
        foreach( Vehicle v in vehicles){
        if(v.Speed>0)
             movingVehicles.Add(v);

        }

        return movingVehicles;
    }

}
}

标签: c#methodsparentderived

解决方案


问题不在于您传递派生类而不是基类;这是允许的。问题是您正在传递一个可变的派生类项目集合,这是不允许的。

幸运的是,您没有将车辆列表视为完整列表:您仅使用其中的一个方面 - 即它的枚举能力。因此,您可以替换List<Vehicle>IEnumerable<Vehicle>,这更“宽容”。特别是,它允许您IEnumerable<Car>在其位置传递 an,只要Car继承自Vehicle

static List<Vehicle> GetMovingVehicles(IEnumerable<Vehicle> vehicles) {
    return vehicles.Where(v => v.Speed != 0).ToList();
}

请注意使用 LINQ 来生成您需要的结果,而无需使用循环。


推荐阅读