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

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

问题描述

有人可以解释为什么在.NET 2.0如果我有一个接口, IPackable 和实现该接口的类 OrderItem List< IPackable> ,传递 List< OrderItem> 不工作?

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 /协变度+和+ 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铸造通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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