Generic Event

In C#, when we need to have an event, we suppose to have a delegate first. Most of the delegate will be defined as the below one if it served for an event;

   1:      public delegate void SignatureRequiredEventHandler(object sender, SignatureRequiredEventArgs args);
   2:      public delegate void SendRequestCompletedEventHandler(object sender, SendRequestCompletedEventArgs args);
   3:      public delegate void HttpRequestdEventHandler(object sender, HttpRequestEventArgs args);
This code is copied from the the NFlickr opensource project.
In my previous post, Software development principle , there is one principle called DRY(Don't Repeat Yourself), it's very obvious this kind of code is already not followed the good practice.
 
.Net now offer a generic event,you can find the MSDN document at http://msdn.microsoft.com/en-us/library/db0etb8x.aspx
 
And we simply don't need the code we just presented.When we declare the event, we just need write the code like
 
   1:   event EventHandler<SendRequestCompletedEventArgs> Complete;
   2:   event EventHandler<HttpRequestCompletedEventArgs> RequestComplete;
   3:   event EventHandler<HttpRequestErrordEventArgs> RequestComplete;
   4:   event EventHandler<SignatureRequiredEventArgs> SignatureRequired;
 
When we register the event, the code should be changed to
 
channel.Complete +=new EventHandler<SendRequestCompletedEventArgs>(channel_Complete);

There are some limitation here.

  1. This generic even only can only replace the delegate which has two parameter , and the first parameter is object and second one is inherited from the EventArgs, basically the generic event only works well when we are going to use the standard event pattern.
  2. This generic event can only replace the delegate which the return value is void. 
 
Published Monday, November 10, 2008 3:53 PM by RobertNet

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)