首页 > 解决方案 > 将子类集合转换为父类列表

问题描述

在其中一个预建类中,我有以下场景

[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
}

如何将子类集合转换为父类列表?

标签: c#.netinheritance

解决方案


您可以使用以下System.Linq.Cast方法:

List<Parent> ToSet = Records.Cast<Parent>().ToList();

这只有在所有物品都可以施放的情况下才会成功,InvalidCastException否则会抛出一个。


推荐阅读