I have developed some software systems using .NET so far. Using Delegates and declaring my own events in classes happened to me really rarely.
I was wondering 开发者_开发技巧if I am missing a powerful mechanism (delegates & events) or they are not really frequently used. If they are, please explain 1 scenario which can not be developed without using delegates and events.
Thank you.
Delegates are mostly just a very convenient way of representing behaviour. You can usually achieve the same thing by declaring a single-method interface... but that would often be a lot more cumbersome to use. (Especially where you would normally combine delegates together, create them with lambda expressions or invoke them asynchronously.)
I find myself declaring events relatively rarely - but using them frequently when writing UI code. I use delegates much more often than that though - for example, LINQ is entirely based on delegates.
I don't think it's really useful to ask for problems which absolutely can't be solved without delegates. It makes more sense to think about problems which are best solved with delegates - and that's a matter of situations where you need to be able to represent a single aspect of behaviour (reacting to a button press, a filter or projection for a collection, the action to take when a thread has started etc) as easily as possible.
EDIT: To expand on the single-method interface comment, imagine this interface:
public interface IEventHandler
{
void HandleEvent(object sender, EventArgs args);
}
With appropriate support classes to combine multiple instances of IEventHandler
into a single one (chaining them together) and a type to represent an "event", you could basically achieve what the EventHandler
delegate does... but in a way which is far harder to use.
精彩评论