C# - Can you loop through types separately in a generic list?

為{幸葍}努か 提交于 2019-12-11 03:53:46

问题


I have 3 different classes, a generic "entity" class, and then two classes that inherit this, a bullet class and an enemy class.

I then have a list of the entity class, with the bullets and enemies in the list, and a lot of the places I treat these the same. However, some times, I want to loop through just one of the classes, and not the other, e.g. Loop through each bullet, but not the enemies. Is there any way to do this?

I tried

foreach (Bullet tempBullet in entities)

But I get the error

Unable to cast object of type 'Enemy' to type 'Bullet'.

Anyone know if this is possible, or do I have to use seperate lists?


回答1:


You can probably use a little Linq:

foreach (var bullet in entities.OfType<Bullet>())
{

}



回答2:


If you're using .NET 2:

foreach (Entity ent in entities) {
    Enemy e = ent as Enemy;
    Bullet b = ent as Bullet;

    if (e != null) {
        // process enemy
    }
    else if (b != null) {
        // process bullet
    }
}

or, using linq (and entities is an object that inherits IEnumerable<T>):

foreach (Bullet bullet in entities.OfType<Bullet>()) {
    // process bullets only
}


来源:https://stackoverflow.com/questions/3958091/c-sharp-can-you-loop-through-types-separately-in-a-generic-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!