Pergunta

I've been searching for a way to call the same method on multiple instances without writing a similar line multiple times.

An example would be :

Class Car(){

Car(){
//stuff
}

Explode(){
//exploding stuff
}

}

So if i want to have 2 - 3 or more Car objects ... say like this ...

Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();

And I want all three cars to explode ... I'd usually do this :

car1.explode();
car2.explode();
car3.explode();

Is there a better way to do this ... one that saves writing all this code ? Some kind of design pattern perhaps ?

Foi útil?

Solução

I'd say push them all into a list of some type and iterate through it.

List<Car> cars = new List<Car>();
cars.Add(car1);
...

foreach (Car car in cars)
{
    car.Explode();
}

Outras dicas

The best way, as far as I know, is to save a list of all the objects you've created. Then create a function called explodeAll, which iterates through the list and calls explode on each object.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top