c# - 将派生类传递给使用父类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;
}
}
}
解决方案
问题不在于您传递派生类而不是基类;这是允许的。问题是您正在传递一个可变的派生类项目集合,这是不允许的。
幸运的是,您没有将车辆列表视为完整列表:您仅使用其中的一个方面 - 即它的枚举能力。因此,您可以替换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 来生成您需要的结果,而无需使用循环。
推荐阅读
- python - 如何在 PyQt5 中使用按键事件
- javascript - 正则表达式和匹配方法
- javascript - 即使使用 ngFor Angular 也列出 2 列
- linux - gnome-shell 3.34 缺少 ExtensionUtils.extension 属性
- python-3.x - 绑定方法的 MyPy 类型注释?
- sql - SQL issue with RIGHT JOINS
- javascript - 如何调用对象的辅助函数?
- javascript - 如何访问组件的 typeof 实例中的成员?
- apache-kafka - 如何将kafka与OPC连接?
- ios - 在 xcode/swift 中使用位置管理器来获取用户的当前位置时,我得到的值为 nil。有什么建议么?