lundi 29 avril 2019

What is the best way to create a simple global event system in C#?

I'm looking to create a quick event system in C# but I'm not sure the best way to approach it. Here's how I would like it to work:

Messenger

This is where I'd like all events to be stored. The class would look something like this:

public static class Messenger
{
    // This event would have a few params, like GameState, Ammo, and Lives, or something
    public static GameStateMessage OnGameStateChanged;

    // This event could be generic, with no args
    public static Message OnGameStarted;
}

Subscribers

I'd like anything to be able to subscribe to these messages by doing something like this:

// Handler, which will be passed to the event
private void OnGameStartedHandler(GameState gameState, int ammo, int lives)
{
    // Do something
}


// Event would be subscribed to like this:
Messenger.OnGameStarted += OnGameStartedHandler;

// or this:
Messenger.OnGameStarted.Subscribe(OnGameStartedHandler);

Dispatchers

Finally, I'd like anything to be able to dispatch any of these events like so:

Messenger.OnGameStarted(gameState, ammoCount, livesCount);

// or

Messenger.OnGameStarted.Invoke(gameState, ammoCount, livesCount);

Is there any way to do something like this easily and cleanly? I'd like for it to be very fast to create new events (without having to create new classes or any boilerplate code)

Basically The Messenger class would act as a central hub for specific events, something that can easily be referenced and managed from a single location.

Aucun commentaire:

Enregistrer un commentaire