开发者

Need concise definition of "delegate"

开发者 https://www.devze.com 2023-01-08 20:30 出处:网络
I need a short description of how \"delegation\" works in programming, preferably 开发者_StackOverflow社区in one sentence. Even better to use analogiesA type-safefunction-pointer.A type safe function

I need a short description of how "delegation" works in programming, preferably 开发者_StackOverflow社区in one sentence. Even better to use analogies


A type-safe function-pointer.


A type safe function pointer.


Even better to use analogies

Delegates are like violence. If they haven't solved your problem yet then you haven't used enough.

OK, this joke is not original, so sue me.

Seriously now. Delegates are like... delegates. Hence the name. What is a delegate in real life? A delegate is someone who acts on behalf of another. You delegate work to them and they perform that work. You want to trade fifty shares of XYZ corp, you don't go down to the trading floor and do it yourself, you delegate that work to your broker who does it for you; how they do it, you don't care so long as it gets done. The broker is your delegate; they do the work on your behalf.

A delegate is an object that represents the ability to do work on demand. You create a delegate that does a particular job, and when you want the job done, you ask your delegate to go do it for you.


A delegate wraps a method into a type safe object reference the way a beer opener wraps a method (opening beer) in a handy tool (the beer opener) that can be used again and again for different kind of beer bottles.

There's input defined for the beer opener, a certain type of bottle and a force (your hands). It holds the key to an action of which the form is always the same. Likewise, there's input defined for the delegate, which holds the key, a contract, to an action (showing a form) with certain input (the form).

Note: this is not about 99 bottles of beer ;)

Note (2): you can open a beer without a beer opener, the same way you can use a method (even its reference) without a delegate. It's just messier and less clear, but it can be a lot more fun though.


The best analogy I can think of comes from the C terminology, which is "pointer to function".

The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose.


A delegate is a type that references a method.


A delegate is like an intern, as in when you say "Hey, I need an intern to bring me a cup of coffee."

With luck you will get someone who is capable of executing "bring me a cup of coffee". Different interns might execute that task differently, one may run out to Starbucks, for example. Another might run around until she finds a non-empty coffee pot somewhere in the building and pour you a cup.

0

精彩评论

暂无评论...
验证码 换一张
取 消