c# - How to dynamically subscribe to an event? -


related


i need detect when event fired. trying subscribe dynamically on event.

the problem have different types of delegates, not events have same signature. solutions provided in here , here expects object sender, eventargs e, not using, exception telling types doesn't match.

here examples of delegates have:

public delegate void oneventa(int id); public delegate void oneventb(double num, string name); 

how can create correct delegate?

eventinfo has method addeventhandler can use. if don't have delegate instance, can create delegate dynamically using delegate.createdelegate:

var eh = delegate.createdelegate(ei.eventhandlertype, target, methodinfo); ei.addeventhandler(owner, eh); 

in example target target object delegate , methodinfo methodinfo of method in target object. finally, owner object event ei belongs.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -