c# - 将子类集合转换为父类列表
问题描述
在其中一个预建类中,我有以下场景
[Serializable, XmlInclude(typeof(Child1)), XmlInclude(typeof(Child2)), XmlRoot(IsNullable=false)]
public abstract class Parent
{
}
[Serializable, XmlRoot(IsNullable=false)]
public class Child1: Parent
{
public string C1{get;set;}
}
[Serializable, XmlRoot(IsNullable=false)]
public class Child2: Parent
{
public string C2{get;set;}
}
void Main()
{
System.Collections.ObjectModel.Collection<object> Records = GetDataFromDb();
//above line returns collection of object containing either Child1 or Child2
List<Parent> ToSet = null;//TODO: convert the child object collection to list of parent
}
如何将子类集合转换为父类列表?
解决方案
您可以使用以下System.Linq.Cast
方法:
List<Parent> ToSet = Records.Cast<Parent>().ToList();
这只有在所有物品都可以施放的情况下才会成功,InvalidCastException
否则会抛出一个。
推荐阅读
- python - 在scrapy中以异步方法发出内联请求时无法使用`headers`或`dont_filter = True`
- awk - 如何使用awk对csv文件中的记录进行排序
- android - 如何在 Chromebook 上的 Android 应用程序的窗口边框上隐藏后退按钮
- css - Sweetalert 2中的输入在材料UI模式反应js中不可输入
- django - 如何使用通用 ListCreateAPIView 在嵌套序列化程序中更新用户及其配置文件?
- javascript - 如何从 dxf 文件解析 nurbs 表面?或者您知道用于解析它的库(对于 js,如果存在或任何其他语言)?
- android-espresso - 用于单击父节点或下一个节点的 Espresso 或 UIAutomation 解决方案
- python - Django User.date_joined.date 使用 UTC 时间?
- python - Python Selenium 并行验证两个元素并单击一个
- android - 如何解决此错误:无法在 Android Studio 中开始监控 emulator-5554