2009-07-02 83 views
0

我有两个类....包裹和FundParcel ......,我想一个IEnumerable转换的子类型的超类型的一个IList的....为什么我不能使用AddRange添加子类项目?

public class FundParcel : Parcel 
{ 
    /* properties defined here */ 
} 

public class Parcel 
{ 
    /* properties defined here */ 
} 

这些在另一个使用在方法类,如下所示:

private IList<Parcel> ExtractParcels(IEnumerable<FundParcel> fundParcels) 
{ 
    var parcels = new List<Parcel>(); 

    foreach (var fp in fundParcels) 
     parcels.Add(fp); 

    return parcels; 
} 

我不明白的是为什么foreach语句不能被简化为:

parcels.AddRange(fundParcels); 

我基本上得到,说:“精氨酸错误ument型'System.Colection.Generic.IEnumerable<FundParcel>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<Parcel>'"

但是,如果是这样的话,那么我不明白为什么parcels.Add工程...

我觉得好像整个方法应该是可更换的与线:

return (List<Parcel>)fundParcels; 

...也许该方法可以报废产品总数自亚型应该是替代其超..

谁能解释这笔交易是用什么的AddRange在这种情况下,为什么for循环可能会在这种情况下,有必要?

+0

可能的重复[为什么C#/ CLR不支持方法重写co/contra-variance?](http://stackoverflow.com/questions/837134/why-does-c-clr-not-support-method- override-co-contra-variance) – TheLethalCoder 2016-06-13 13:30:35

回答

4

This SO可能会回答你的问题,也会指出你即将到来的C#4.0的参考资料,它将在一定程度上支持共同/反方差。

+0

那么这是一个将在C#4.0中解决的已知问题? – mezoid 2009-07-02 05:14:27

1

考虑以下代码:

void AddParcelToParcelList(List<Parcel> parcels) { 
    parcels.add(new Parcel()); 
} 

List<FundParcel> fundParcels = new List<FundParcels>(); 
AddParcelToParcelList(fundParcels); 

如果继承的类也从基类的容器继承,上面的代码将是有效的,并且产生的情况下的容器,其中继承的类的列表包含对象的基类。

相关问题