tags:

views:

36

answers:

2

I've got a list of identical (signature-wise) events (25+):

public class SourceOfManyEvents {    

    public event Action<EventInfo> FirstEvent = delegate { };
    public event Action<EventInfo> SecondEvent = delegate { };
    {...}
}

I know that more events will be added to the class down the road using the same signature. I'm keen to do some logging when the events fire so I want to bind all the events to a single logging event handler like this:

// PSEUDO-CODE WARNING! :D
// PSEUDO-CODE WARNING! :D
// PSEUDO-CODE WARNING! :D

public void BindToAllEvents(SourceOfManyEvents source) {    

    var events = typeof(SourceOfManyEvents).GetEvents();

    foreach (var e in events) {
        e.BindToEvent(source, GenericEventHandler);
    }
}

public void GenericEventHandler(EventInfo info) {
    // do some logging here
}

Is there a way to achieve this using .Net 4 & C#?

+2  A: 

Something like this?

    public static void GenericEventHandler(EventInfo info)
    {
        // do some logging here
    }

    public static void Bind(SourceOfManyEvents s)
    {
        foreach (var e in typeof(SourceOfManyEvents).GetEvents())
        {
            e.AddEventHandler(s, (Action<EventInfo>)GenericEventHandler);
        }
    }
desco
A: 

It is definatly possible, also you might have to use reflection to do this. I'm not completly sure this is correct, since it has been a while since i used reflection but i would try this:

 var events = typeof(SourceOfManyEvents).GetEvents();
 foreach (var e in events) {
    e.AddEventHandler(source, (Action<EventInfo>) GenericEventHandler);
}
Grizzly