Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Are delegates the same thing as callbacks? Or are they related somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
336 views
Welcome To Ask or Share your Answers For Others

1 Answer

A "callback" is a term that refers to a coding design pattern, available in any language that has function pointers, or an analogue to function pointers (which is kinda what a delegate is)

In this pattern, you pass a pointer to a function to another function, so that within the called function, it can "call back" the function you passed to it. In this way you can control a large chunk of the internal behavior of a method from outside the method, by passing pointers to different "callback" function each time you call it... An example of a callback is when you have a sorting algorithm that has to be passed a pointer to a function that will "compare" any arbitrary pair of objects in the list to be sorted, to determine which goes before the other. On one call to the sort method, you might pass a callback function that compares by object name, and another time pass a function that compares by object weight, or whatever...

A Delegate, otoh, is a specific .Net type that acts as a signature-specific container for a function pointer... In .Net managed code, delegates are the only way to create and use a function pointer. So in .Net to do a callback, you are in fact passing a delegate... But delegates can be used in other scenarios besides callbacks. (specifically, delegates can be also used to implement multi-threading from the .Net thread pool)

Callbacks are also used to implement the "observer" pattern (implemented in .Net using Events, which are themselves a special type of delegate)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...