我有兩個類....包裹和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