为什么我不能使用 AddRange 添加子类项?
我有两个类...Parcel 和 FundParcel...我正在尝试将子类型的 IEnumerable 转换为超类型的 IList...
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);
我基本上得到一个错误,上面写着“Argument type 'System.Colection.Generic.IEnumerable
但如果是这样的话,那么我不明白为什么 Parcels.Add 起作用......
我觉得整个方法应该可以用以下行替换:
return (List<Parcel>)fundParcels;
...或者也许该方法可以一起废弃,因为子类型应该可以替代它们的超类型..
任何人都可以解释一下在这种情况下 AddRange 的处理方式以及为什么在这种情况下可能需要 for 循环案件?
I have two classes.... Parcel and FundParcel...and I'm trying to convert an IEnumerable of the subtype to an IList of the supertype....
public class FundParcel : Parcel
{
/* properties defined here */
}
public class Parcel
{
/* properties defined here */
}
These are used in another class in a method as follows:
private IList<Parcel> ExtractParcels(IEnumerable<FundParcel> fundParcels)
{
var parcels = new List<Parcel>();
foreach (var fp in fundParcels)
parcels.Add(fp);
return parcels;
}
What I don't understand is why the foreach statement can't be reduced to:
parcels.AddRange(fundParcels);
I basically get an error that says "Argument type 'System.Colection.Generic.IEnumerable<FundParcel>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<Parcel>'"
But if that's the case then I don't understand why parcels.Add works...
I feel as though the entire method ought to be replaceable with the line:
return (List<Parcel>)fundParcels;
...or maybe the method can be scrapped alltogether since subtypes should be substitutable for their supertype..
Can anyone explain what the deal is with AddRange in this case and why the for loop may be necessary in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能会回答您的问题问题,并且还将向您指出有关即将推出的 C# 4.0 的参考资料,它将在一定程度上支持 Co-/Contra-variance。
This SO will probably answer your question and also will point you to references about upcoming C# 4.0 which will support Co-/Contra-variance to a certain degree.
考虑以下代码:
如果继承类的容器也从基类的容器继承,则上述代码将有效,并生成继承类的列表包含基类的对象的情况。
Consider this code:
If containers of inherited classes also inherited from containers of the base classes, the above code would be valid, and generate a case where a list of the inherited class contains an object of the base class.