繁体   English   中英

将子类集合转换为父类列表

[英]Converting child class collection to list of parent class

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

[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

琐碎的。

System.Collections.ObjectModel.Collection<object> Records = GetDataFromDb();
//above line returns collection of object containing either Child1 or Child2 
List<Parent> ToSet = Records.OfType<Parent>().ToList();

Cast相比,它不会返回无法转换为Parent的实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM