What is delegate?
Delegate is a type that can associate with any method with compatible signature. It's like pointer to function.
Delegate declaration and usage
1. Declare: delegate signature(parameters)
public delegate void ProcessBookDelegate(Book book);3. Subscriber method and Invoke: SubscriberMethod(delegate name)
2. Instantiate delegate instance and associate with handler method
bookDB.ProcessPaperbackBooks(PrintTitle);
bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal);
public void ProcessPaperbackBooks(ProcessBookDelegate processBook)The above example in details. What the code achieved is call different method via a common method (depending on the which method is associated with the delegate)
{
processBook(mybook);
}
http://msdn.microsoft.com/en-us/library/ms173176.aspx
What are the type of delegates?
- Covariance - delegates can be used with methods that have return types that are derived from the return type in the delegate signature. In other words, the delegate signature can returns type of base class or inherited type.
- Contravariance - subscriber can use the same delegate to handle different method as long as the delegate signature base type is the same. A muticasting example, Base class - Vehicle has children class Truck and Car. Subscriber class -
.OnTheMove += Truck.Move + Car.Move.
1. Object type is passed in at run-time.
public delegate void DelFurther reading:(T item);
public void Notify(int i) { }
Del<int> d2 = Notify;
MSDN Delegate reference guide
http://msdn.microsoft.com/en-us/library/ms173174.aspx
Simple Direct Examples
http://www.akadia.com/services/dotnet_delegates_and_events.html
No comments:
Post a Comment