如何将基本类型的列表转换为派生类型的列表 [英] How to cast a list of a base type to list of the derived type

查看:40
本文介绍了如何将基本类型的列表转换为派生类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There seems to be a number of questions going the other way, from a derived class to a base class but my issue is how to cast a list of a base type to list of the derived type?

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
}

我最终得出的解决方案不是很好.

Solution I ended up with which is not very elegant.

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

一定有更好的方法...

There must be a better way...

推荐答案

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

You can use Linq method OfType<MyDerived>(), e.g.:

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

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

It will remove all the items which are not MyDerived class though

这篇关于如何将基本类型的列表转换为派生类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆