如何通过一个List<儿童与GT;与参数列表℃的方法;家长和GT ;? [英] How to pass a List<Child> to a method with parameter List<Parent>?

查看:126
本文介绍了如何通过一个List<儿童与GT;与参数列表℃的方法;家长和GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经离开继承了一段时间,需要一点点的援助之手。

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

我有一个抽象基类首席。有两种继承类船舶,它通过首席分享几个属性

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);

我是假设,当然是,名单,其中,车辆和GT; 将被视为一个名单,其中,首席&GT; 时,作为参数传递给 AssignRandomProperties ,但显然不是。难道列表需要转换为名单,其中,首席&GT; 第一?如果是这样,怎么样?

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?

推荐答案

一是一些解释。您不能转换名单,其中,车辆和GT; 名单,其中,首席&GT; 因为那时Add方法将有签名无效名单,其中,首席&GT;。新增(首席项目),你将能够存储在一个列表中的首席类的实例是被宣布为唯一持有秒。这将破坏型系统;因此它是不允许的。

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&LT;首席&GT;()。然而,这将创建一个新的列表。这有两个含义:(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&LT;儿童与GT;与参数列表℃的方法;家长和GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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