Question

Je cet extrait

private void westButton_click(object sender, EventArgs ea)
{
    PlayerCharacter.Go(Direction.West);
}

répétée pour le Nord, du Sud et de l'Est.

Comment puis-je déclarer une fonction qui me laisserait générer des méthodes comme ir programmation?

par exemple. Je voudrais pouvoir appeler

northButton.Click += GoMethod(Direction.North);

au lieu de définir le procédé, puis

northButton.Click += new EventHandler(northButton.Click);
Était-ce utile?

La solution

northButton.Click += (s, e) => GoMethod(Direction.North);

(ou ...)

northButton.Click += (s, e) => PlayerCharacter.Go(Direction.North);

Autres conseils

Il me semble avoir trouvé une solution:

private EventHandler GoMethod(Direction dir)
{
    return new EventHandler((object sender, EventArgs ea) => PlayerCharacter.Go(dir));
}

Mon seul souci serait temps contraignant; si PlayerCharacter est null quand je l'appelle GoMethod, ce qui se passerait?

northButton.Click += (s,e) => GoMethod(Direction.North);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top