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.
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.
- 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.
- This generic event can only replace the delegate which the return value is void.