Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Delegates Example
Message
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Divers
Thread ID:
01382648
Message ID:
01382711
Vues:
40
>I think have the workings of Datagates down ok, except I cant for the life of me see a use for one.
>
>One web site asked "Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time."
>
>How would you not know the name of the method? What I need is a serious example.
>
>Anyone?

Well, they're required for any type of event - that's a fairly practical use, no? What good is any user control w/o events that you can hook into to know when someone has clicked on something, typed something in, etc. Delegates are what make them possible. You publish an event using a delegate - the delegate provides the signature (that is, what parameters the event will pass) that any subscriber must accept. It also holds a list of subscribers to the event. When you fire an event it essentially tells the delegate to notify anyone that might be listening that the event occurred.

The framework kind of hides the fact that a delegate is basically just another class. Take a look at how an event is declared:
public event SomeDelegateName MyEvent;
Drop the "event" keyword:
public SomeDelegateName MyEvent;
That looks just like how you'd set up a member on a class, which makes sense since that's really what it is. It's a class which maintains a list of people interested in that event. When you "hook up" to an event:
someObject.ClockTickEvent += methodToHandleClockTick();
The framework is basically instanciating a delegate and calling a method on it passing in a reference to the method which will respond to that event. The delegate adds that reference into an internal list. When you fire the event:
if (ClockTickEvent != null)
   ClockTickEvent();
It tells the delegate to walk the list and notify the subscribers. Thinking about it that way, it also starts to make sense as to why you need to check to see if the event is null before firing it. The delegate isn't created until the first person subscribes to the event. Basically, in the .NET world, if a tree falls in the forest and no one is around to hear it, it doesn't make a sound.

(this is all basically the simplest usage of delegates - there are actually a ton of other things you can do with them that aren't really obvious).
-Paul

RCS Solutions, Inc.
Blog
Twitter
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform