【问题标题】:Converting child class collection to list of parent class将子类集合转换为父类列表
【发布时间】:2020-03-23 20:05:09
【问题描述】:

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

[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# .net inheritance


    【解决方案1】:

    微不足道。

    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的实例。

    【讨论】:

      【解决方案2】:

      你可以使用System.Linq.Cast方法:

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

      只有在所有项目都可以施放时才会成功,否则会抛出InvalidCastException

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        相关资源
        最近更新 更多