簡體   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