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

ベースのリストを派生のリストにキャストすることは、基本的にタイプセーフではありません。

コードは base のリストを派生のリストにコピーします。

もっと簡単にそれを行うことができます:

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 に答える