【发布时间】:2016-04-18 19:01:51
【问题描述】:
我想将列表的对象转换为它的子类。 为此我使用了Casting populated List<BaseClass> to List<ChildClass>
现在,当我执行代码时,我总是在 System.Core.dll 中收到 InvalidCastException ""对象项无法转换为子项"
[Serializable]
public class SubItem: Item
{
public SubItem(int id) : base( id)
{
}
}
public getStuff(int id){
//where the Error is thrown
//Inventory has Items in it, furthermore atm Inventory is definitely not empty, but could be later on
var items = Inventory.FindAll(x=> x.id==id).Cast<SubItem>().ToList();
}
项目来自 API,我无法在那里更改任何内容。 项目继承自 IEquatable。
LINQ 确实可以工作,但是当我进行投射时,我得到了错误。我做错了什么?
【问题讨论】:
-
你有错字
public SubItem(ind id) : base( id) -
您的库存包含物品或子物品?
-
int id而不是ind it。但这应该是一个错字,否则它不会编译(没有class ind..)。正如我猜测的那样,您正在尝试将Item转换为SubItem,这是不可能的。您可能想检查实例是否为typeof(SubItem)? -
列表中的对象具有匹配的
id,但实际上不是子项。也许您需要 OfType,也许这是一个错误。 -
Inventory.FindAll(x=> x.id==id).ToList
()