by
15. July 2008 15:17
In some articles like this and this we can see how to 'trace' event.
This article show you another way to do this.
When we need to handle an event we need some method with the same signature as event delegate.
Of course we can't statically write all possible methods. So we come to two ways:
1. Limit ourselves with few delegates
2. Use dynamic code generation
In .net we can do code generation in two ways:
1. Language code provider like CsharpCodeProveder
2. Reflection.Emit namespace
I've used Reflection.Emit with DynamicMethod
Client code must provide object, event (or event name) and method that will be called when event fired.
limitations
1. Static events not supported (easy task)
2. Non void return events not supported (for now looks hard)
updates (11/21/2008)
1. Static events support added
2. Fixed bug with value types boxing
How to handle non void return?
Well lets think that classic events are just notifications.
And events that returns value - special facility for special case. Which means we can't predict the reaction of code that fired the event if we'll return something by default(usually null).
If we just return null (for common case - not all types have parameterless constructor) we may change object(sender) internal state since that object knows nothing about our hooking.
So there is no general approach to handle such a type of events.
Source Code [Downloads: 74]
89671a70-9b13-46fc-a8af-087c1dde84f1|0|.0
Tags: c#
My code