从派生类到基类,似乎有很多问题相反,但我的问题是如何将基类型列表转换为派生类型列表?
public class MyBase {
public int A;
}
public class MyDerived : MyBase {
public int B;
}
public void MyMethod() {
List<MyBase> baseCollection = GetBaseCollection();
List<MyDerived> derivedCollection = (List<MyDerived>)baseCollection; // Which doesn't work
}
我最终得到的解决方案不是很优雅。
public class MyBase {
public int A;
}
public class MyDerived {
public int B;
public MyBase BASE;
}
public void MyMethod() {
List<MyBase> baseCollection = GetBaseCollection();
List<MyDerived> derivedCollection = new List<MyDerived>();
baseCollection.ForEach(x=>{
derivedCollection.Add(new derivedCollection(){ BASE = x});
});
}
一定会有更好的办法...