开发者

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

I have 3 different classes, a generic "entity" class, and then two classes that inherit this, a bullet class and an e开发者_C百科nemy 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?


You can probably use a little Linq:

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

}


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜