如何传递 List<Child>到带有参数 List<Parent> 的方法? [英] How to pass a List&lt;Child&gt; to a method with parameter List&lt;Parent&gt;?

查看:12
本文介绍了如何传递 List<Child>到带有参数 List<Parent> 的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一段时间没有继承遗产了,需要一点帮助.

I've been away from inheritance for a while and need a little helping hand.

我有一个抽象基类Chief.有两个继承类ShipVehicle,它们通过Chief共享几个属性.

I have an abstract base class Chief. There are two inheriting classes Ship and Vehicle, which share several properties via Chief.

我有一个使用这些通用属性的方法:

I have a method which uses those common properties:

public static void AssignRandomProperties(PSetList routeSettings, List<Chief> theChiefs)

但是当我尝试传递一个

but when I try to pass a

List<Ship> 

List<Vehicle> 

我听说它们无法转换.这是一个示例方法调用:

I'm told that they can't be converted. Here's a sample method call:

ChiefRouteRandomizer.AssignRandomProperties(s.Route, theVehicles);

我当然假设 List 在作为参数传递给 AssignRandomProperties 时将被视为 List>,但显然不是.列表是否需要先转换为List?如果是,怎么办?

I was assuming of course that the List<Vehicle> would be treated as a List<Chief> when passed as the argument to AssignRandomProperties, but apparently not. Does the list need converting to List<Chief> first? If so, how?

推荐答案

首先说明一下.您不能将 List 转换为 List 因为这样 Add 方法将具有签名 void List.Add(Chief item) 并且您将能够将 Chief 类的实例存储在声明为仅包含 Vehicle 的列表中.这会破坏类型系统;因此是不允许的.

First some explanation. You cannot convert List<Vehicle> to List<Chief> because then the Add method would have the signature void List<Chief>.Add(Chief item) and you would be able to store instances of the Chief class in a list that was declared to only hold Vehicles. This would break the type system; therefore it is not allowed.

解决这个问题的最简单方法是传入theVehicles.ToList().但是,这将创建一个新列表.这有两个含义:(1) 复制列表会浪费内存,以及 (2) 如果该方法要改变列表本身(添加/删除项目或用其他成员替换成员),您将看不到这些更改在 theVehicles 列表中.(如果列表中的引用指向的对象是唯一被修改的东西,这不是问题.)

The easiest way to get around this is to pass in theVehicles.ToList<Chief>(). However, this will create a new list. This has two implications: (1) You would be wasting memory by duplicating the list, and (2) if the method is going to mutate the list itself (add/remove items or replace members with other members) you will not see those changes on the theVehicles list. (If the objects the references in the list point to are the only things being modified, this is not a problem.)

如果您可以控制 AssignRandomProperties 方法,请考虑改用此签名:

If you have control over the AssignRandomProperties method, consider using this signature instead:

public static void AssignRandomProperties<T>(
    PSetList routeSettings,
    IList<T> theChiefs) where T : Chief
{
    ...
}

这篇关于如何传递 List<Child>到带有参数 List<Parent> 的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆