我有两个类....包裹和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循环可能会在这种情况下,有必要?
可能的重复[为什么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