我想知道是否可以将两个不同类型但都具有相同super
类的列表合并在一起
public class A : super {}
public class B : super {}
ListA<super> ListA = new List<super>();
ListA<B> ListA = new List<B>();
我想将这两个列表组合成如下内容:
List <super> ListCombined = new List <super>();
还要注意,A
和B
具有相同的super
类
发布于 2019-08-01 20:44:36
您可以尝试Linq
ListCombined = ListA
.OfType<super>()
.Concat(ListB)
.ToList();
或AddRange
(无Linq解决方案):
List<super> ListCombined = new List<super>();
ListCombined.AddRange(ListA);
ListCombined.AddRange(ListB);
发布于 2019-08-01 20:58:36
可能:
using System;
using System.Collections.Generic;
public static class Program {
public static void Main() {
List<ExtendedCar1> cars1 = new List<ExtendedCar1>{
new ExtendedCar1{Brand = "Audi", Model = "R8"},
new ExtendedCar1{Brand = "Bentley", Model = "Azure"}
};
List<ExtendedCar2> cars2 = new List<ExtendedCar2>{
new ExtendedCar2{Brand = "Ferrari", Color ="Red"},
new ExtendedCar2{Brand = "Maruti", Color ="Saffire Blue"}
};
List<Car> cars = new List<Car>(cars1);
cars.AddRange(cars2);
foreach(var car in cars){
Console.WriteLine($"Car Brand: {car.Brand}");
}
}
}
public class Car{
public String Brand {get;set;}
}
public class ExtendedCar1 : Car {
public String Model{get;set;}
}
public class ExtendedCar2: Car {
public String Color {get;set;}
}
输出:
发布于 2019-08-01 20:51:57
我猜你说的超级是指基类?
public class Parent
{
public List<ChildA> ChildListA { get; set;}
public List<ChildB> ChildListB { get; set;}
}
public class ChildA:Parent
{
}
public class ChildB:Parent
{
}
var parentList= new List<Parent>();
parentList.Add( new Parent() { ChildListA=new List<ChildA>(), ChildListB=new List<ChildB>()});
// assuming parent is not abstract
https://stackoverflow.com/questions/57309257
复制相似问题