.NET铸造泛型列表 [英] .NET Casting Generic List

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

问题描述

有人能向我解释为什么在.NET 2.0,如果我有一个接口, IPackable 和一个类实现该接口订单项,当我有一个方法,需要在名单,其中,IPackable> ,传递的名单名单,其中,订单项> 不工作?

有谁知道我能做到这一点的功能?

code:

 公共接口IPackable {
        双重量{获得; }
}

公共类订单项:IPackable


公开名单< IShipMethod> GetForShipWeight(名单< IPackable>包){
   双totalWeight = 0;
   的foreach(IPackable包套餐){
        totalWeight + = package.Weight;
   }
}
 

下面code不起作用。

 名单,其中,订单项>的OrderItems =新的名单,其中,订单项>();
名单< IShipMethod> shipMethods = GetForShipWeight(的OrderItems);
 

解决方案

该功能被称为协方差/逆变,将在C#4.0的支持。你可以在这里阅读有关:<一href="http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx">http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

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?

Code:

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

The following code does not work.

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

解决方案

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天全站免登陆