问题
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