c# - 将派生类传递给使用父类 C# 的方法

标签 c# methods parent derived

今天我参加了测试,其中的任务是将静态方法 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;
    }

}
}

最佳答案

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

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

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

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

关于c# - 将派生类传递给使用父类 C# 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50475735/

相关文章:

c# - 使用 P/Invoke 获取字符串

java - 如何定义返回参数?

javascript - jQuery 选择元素的父级并为其使用 prependTo()

javascript - 除了所选的 child 之外,将类(class)应用于 child 的 parent - JQuery

javascript - open.window后禁用父窗口

c# - 如何使 Windows Phone 应用程序像默认应用程序一样加载得更快?

c# - 字符串连接是在内存中为链中的每个字符串分配新字符串,还是仅为被更改的字符串分配新字符串?

c# - FakeItEasy 不验证完整框架 SignalR 测试的调用

java - 给定一个数字,打印接下来的三个数字

java - 创建包含新实例的列表的方法的命名