Are delegates and callbacks the same or similar?

2019-01-16 17:40发布

问题:

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

回答1:

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)



回答2:

(I assume you're talking about .NET here. If not, please elaborate.)

Delegates are the idiomatic way of implementing callbacks in .NET - but you don't have to. You could use an interface, for example. (In particular you could then have one callback with one method to call on error, and one on success. Of course, you could take two delegates instead...)

There are plenty of uses for delegates beyond callbacks in .NET - it depends on exactly what you deem to be a callback, but GUI event handlers, thread-starters, filters and projections (and more!) in LINQ to Objects all use delegates.



回答3:

generically, a delegate is an object used to access a method external to the object owning the method, while a callback is a variable that holds a delegate

in C#, the terms are used interchangeably



回答4:

They are hand in hand related. A delegate is the description on how the callback function looks like:

delegate void MyDelegate(string Text);

Then you can have a function that can take in the callback as a parameter.

//This will result in a MessageBox with "Lalalala"
MyFunctionThatGetsTheCallbackFunctionRef(MyCallBackFunc); 

void MyFunctionThatGetsTheCallbackFunctionRef(MyDelegate TheFunction){
 TheFunction("Lalalala");
}

void MyCallBackFunc(string Text){
  //my callback
  MessageBox.Show(Text);
}