c# - 遍历具有相同基类的对象列表并提取某个类?

标签 c# class object inheritance

例如,我有一个基类Entity ,然后派生自此的两个子类,LightEntityPlayerEntity .

然后我有一个 List<Entity> Entities拥有 LightEntity s 和 PlayerEntity

我希望获得所有 LightEntity来自 Entities .

我试过:

List<LightEntity> lights = new List<LightEntity>();
foreach (Entity ent in Entities)
{
    if(ent is LightEntity)
    {
        lights.Add(ent);
    }
}

但它不喜欢这样,因为编译器似乎仍然认为它可能会尝试只添加一个 Entity。到 LightEntity 的列表.

我试着投 entLightEntity但是编译器说它没有转换 Entity 的方法到 LightEntity .

最佳答案

你可以使用 OfType按类型过滤实体:

List<LightEntity> lights = new List<LightEntity>();
lights.AddRange(entities.OfType<LightEntity>());

或者更简单:

List<LightEntity> lights = entities.OfType<LightEntity>().ToList();

延伸阅读

关于c# - 遍历具有相同基类的对象列表并提取某个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16471397/

相关文章:

c# - 如何使用 Lucene.net 实现自定义过滤器?

c# - 受密码保护的 SQLite 数据库

c# - 在 C#/ASP.Net 中以编程方式添加对象或更改其参数

c# - 对象是否有属性

javascript - 在 js 库中 $.something (object) 怎么也可以是 $ ("something") (一个函数)?

c# - 如何确保嵌入式浏览器控件使用 Internet Explorer 9?

c# - 在构建时数据类型未知时将数据对象映射到合适的 ViewModel

java - 如何解决 "Exception in thread "AWT-EventQueue-0"java.lang.NullPointerException"?

php - 避免使用无效参数实例化对象

jquery - 单击时的简单切换类不适用于表格