A Developer WeBLOG RSS 2.0

In my previous blog post, I had a solution to prevent subtle bug when removing and readding an event handler. The solution works, but its not flexible at all. You can see the method is very dependent/attached to the button1 object and the click event, which means that the logic cannot be re-use for other objects or other events. For example, if I want to have the same logic for textchanged, this would mean I have to write another function for the event.

So how can we make it more modular? Well, we need to be able to register and unregister event handler dynamically. This can be easily achieved by using reflection and delegates. Reflection alows us to browse all the events that a type have in a form of EventInfo object. We can then use the EventInfo object to add or remove event handler to the event. To do it, EventInfo requires a delegate of the EventHandler type that represents/points to an instance method to invoke on a class instance. The delegate can be created using Delegate.CreateDelegate method, which takes in the following as its parameters: The type of the delegate, An object that contains the event handler method, the event handler method name. Here is the new code of the Register Click Event.

RWendi

Wednesday, January 21, 2009 11:10:17 AM UTC |  Comments [0]
.NET | c# | Programming
All Content © 2012, RWendi