委托和回调是否相同或相似? [英] Are delegates and callbacks the same or similar?

查看:18
本文介绍了委托和回调是否相同或相似?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

委托和回调是一回事吗?或者他们有什么关系?

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

推荐答案

回调"是指编码设计模式的术语,可用于任何具有函数指针的语言,或类似于函数指针(即有点像代表)

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)

在这种模式中,您将一个函数的指针传递给另一个函数,以便在被调用的函数中,它可以回调"您传递给它的函数.通过这种方式,您可以从方法外部控制方法的大部分内部行为,方法是在每次调用时传递指向不同回调"函数的指针......回调的一个例子是当你有一个排序算法时必须传递一个指向函数的指针,该函数将比较"要排序的列表中的任意一对对象,以确定哪个在另一个之前.在对 sort 方法的一次调用中,您可能会传递一个按对象名称进行比较的回调函数,而另一次则传递一个按对象权重进行比较的函数,或者其他...

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...

委托,otoh,是一种特定的 .Net 类型,它充当函数指针的签名特定容器...在 .Net 托管代码中,委托是创建和使用函数指针的唯一方法.所以在 .Net 中做回调,其实是传递了一个委托……但是除了回调之外,委托还可以用在其他场景中.(具体来说,delegate 也可以用来从 .Net 线程池中实现多线程)

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)

回调也用于实现观察者"模式(在 .Net 中使用事件实现,事件本身是一种特殊类型的委托)

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

这篇关于委托和回调是否相同或相似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆