Where to use events and delegates?
I used events and delegates in many of my projects,but still i am having some doubts in my mind where to use the events and delegates in a project and what is the difference between a delegate and an event.Can anyone explain it please?开发者_运维技巧
A Delegate is a type that can encapsulate a method call. You should use a delegate when you want to treat the method as an object and pass it around.
An Event is just a way of exposing a delegate as a property to which any code outside your class can attach their handlers but cannot invoke the delegate. If you expose your delegate as a public property, code outside your class can not only attach their handlers but also invoke the delegate.
In addition Events also allow you to add remove methods which are called when the handlers are attached\detached to it, just like the getter and setter of a public property allowing you to control the process better.
You should use event when you want other classes to subscribe to an event in your class and be notified when it happens.
public delegate void MyMessageHandlerType(string message);
public class EventTest
{
public event MyMessageHandlerType MessageEvent
{
add { } // invoked when MessageEvent += SomeMethod
remove { } // invoked when MessageEvent -= SomeMethod
}
}
Both delegates and events provide a callback mechanism. An event provides a callback mechanism that is somewhat less connected than a delagate, in that it may have any number of attached handlers, and that the code often works the same way regardless of the number of handlers (if any). A good example could be a Resized
event of a window; the window resizing will work whether or not there are any event handler connected; the event is a notification mechanism.
A delegate is more connected in many senses. Typically you can associate exactly one method with a delegate member, and often they are expected; take the LINQ extension methods (such as Where
) for instance: they will not work unless you provide exactly one method for the delegate parameter.
精彩评论