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