dimanche 9 juin 2019

How to group C# custom events

I have a number of custom events that a class might or might not subscribe to.

Action<Game1, MoveEventArgs> MoveEvent;
Action<Game1, InitializeEventArgs> InitializeEvent;
Action<Game1, DrawEventArgs> DrawEvent;
Action<Game1, LoadContentEventArgs> LoadContentEvent;

I would like to bundle these in someway so I can easily pass them into other functions. Such as in a list or dictionary.

I have come up with two solutions. The first is to change my event declarations from:

Action<Game1, InitializeEventArgs> InitializeEvent;
public virtual void Initialize(object o, InitializeEventArgs e) { }

to:

Action<Game1, EventArgs> InitializeEvent;
public virtual void Initialize(object o, EventArgs e) 
{ 
    InitializeEventArgs initializeEventArgs = (InitializeEventArgs)e; 
}

This will allow me to create data stuctures using the type Action<Game1, EventArgs> but will mean I lose the typing on my event subscriber methods possibly resulting in cast exceptions.

The second is creating a struct with my Events in with I can pass to classes.

public struct Events
{
    public Action<Game1, MoveEventArgs> MoveEvent { get; set; }
    public Action<Game1, InitializeEventArgs> InitializeEvent { get; set; }
    public Action<Game1, DrawEventArgs> DrawEvent { get; set; }
    public Action<Game1, LoadContentEventArgs> LoadContentEvent { get; set; }
}

Which I can then use to subscribe to the event in the appropriate class/method using:

Events.InitializeEvent += Initialize;

This seems good but it could potentially become a very large struct especially if I were to have a large number of events.

So I guess my main question is does anyone have improvements for these ideas or something different?

Aucun commentaire:

Enregistrer un commentaire