.NET Casting 通用列表 [英] .NET Casting Generic List

查看:22
本文介绍了.NET Casting 通用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个接口,IPackable 和一个实现该接口的类 OrderItem,当我有一个方法时,有人可以向我解释为什么在 .NET 2.0 中在 List 中,传入 List 的列表不起作用?

Can someone explain to me why in .NET 2.0 if I have an interface, IPackable and a class that implements that interface OrderItem, when I have a method that takes in a List<IPackable>, passing in a list of List<OrderItem> does not work?

有谁知道我如何实现这个功能?

Does anyone know how I could accomplish this functionality?

代码:

public interface IPackable {
        double Weight{ get; }
}

public class OrderItem : IPackable


public List<IShipMethod> GetForShipWeight(List<IPackable> packages) {
   double totalWeight = 0;
   foreach (IPackable package in packages) {
        totalWeight += package.Weight;
   }
}

以下代码不起作用.

List<OrderItem> orderItems = new List<OrderItem>();
List<IShipMethod> shipMethods = GetForShipWeight(orderItems);

推荐答案

该功能称为协变/逆变,将在 c# 4.0 中得到支持.您可以在此处阅读:http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

The feature is called covariance/contravariance and will be supported in c# 4.0. You can read about it here: http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

这篇关于.NET Casting 通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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