.NET铸造通用列表 [英] .NET Casting Generic List
问题描述
有人可以解释为什么在.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屋!