3

从派生类到基类,似乎有很多问题相反,但我的问题是如何将基类型列表转换为派生类型列表?

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});
    });
}

一定会有更好的办法...

4

4 回答 4

6

您可以使用 Linq 方法OfType<MyDerived>(),例如:

List<MyDerived> derivedCollection = baseCollection.OfType<MyDerived>().ToList();

它将删除所有不是MyDerived类的项目

于 2013-03-07T14:48:18.033 回答
3

基类列表转换为派生类列表基本上是非类型安全的。

您的代码将基础列表复制到派生列表。

你可以更简单地做到这一点:

List<MyDerived> derivedCollection = baseCollection.ConvertAll(x => new derivedCollection(){ BASE = x});
于 2013-03-07T14:47:32.543 回答
3
using System.Linq;

// with exception in case of cast error
var derivedCollection = baseCollection.Cast<MyDerived>().ToList();

// without exception in case of cast error
var derivedCollection = baseCollection.OfType<MyDerived>().ToList();
于 2013-03-07T14:48:26.247 回答
1

尝试这个:

public class MyBase
{
    public int A;
}

public class MyDerived : MyBase
{
    public int B;

    public MyDerived(MyBase obj)
    {
        A = obj.A;
    }
}


public void MyMethod() {
    List<MyBase> baseCollection = GetBaseCollection();
    List<MyDerived> derivedCollection = baseCollection.Select(x => new MyDerived(x)).ToList();
}
于 2013-03-07T15:00:24.073 回答