我有一个 List<>
包含不同类型对象的抽象对象。
我正在尝试获取某种类型的所有项目并将这些项目设置为它们自己的 List<>
.
这是行不通的-
//myAbstractItems is a List<myAbstractItem>
//typeAList inherents from myAbstractItem
var typeAList = ((List<itemTypeA>)myAbstractItems.Where(i => i.GetType() == typeof(itemTypeA)).ToList());
类型转换(List<itemTypeA>)
似乎失败了。
最佳答案
var typeAList = myAbstractItems.OfType<itemTypeA>().ToList();
从文档...
The OfType(IEnumerable) method returns only those elements in source that can be cast to type TResult.
关于c# - 从抽象类型列表中获取特定类型的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17837367/