I am trying to write a generic "Subscribe" function that will take an object, and add an event handler to a given event name passed as a string. Firstly, I am not sure how to pass the handler method and which type should it use to accept methods with different number of arguments.
I have to mention that these are COM objects from Interop. library, by themselves don't have event definitions and require a cast to the appropriate Event interface. So I can't use reflections to ask the objects about which Events it has.
public void Subscribe(object target, string event_name, Action<object> handler)
{
// find the event
EventInfo info = GetType().GetEvent(event_name); // assume this works and we get the eventinfo back
// create new delegate
Delegate d = Delegate.CreateDelegate(info.EventHandlerType, handler); // this is not correct
info.AddEventHandler(target, d);
}
The callee of the Subscribe function guarantees to pass a function with correct number/type of arguments.
Subscribe(target, "Activated", HandleActivated);
public void HandleActivated(object sender)
{
Console.WriteLine("Activated Handled");
}
The AddEventHandler target object might need a cast to the COM interop event interface. I would like to be able to do this without casting, but don't know of a way to do so. I.e:
((_ISomeEvents_Event)target) // this allows me to get to individual events
What would be the correct way to do this? Having COM Interop in the middle is making the matters worse, but that's what I have.
Aucun commentaire:
Enregistrer un commentaire