代理和回调是相同还是类似? [英] Are delegates and callbacks the same or similar?

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

问题描述

代理是否与回调相同?

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

A Delegate,otoh是一个特定的.Net类型,它充当函数指针的签名特定容器。在.Net托管代码中,委托是创建和使用函数指针的唯一方法。所以在.Net中做一个回调,你事实上是传递一个委托...但委托可以在除回调之外的其他场景中使用。 (具体来说,委托也可以用于从.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天全站免登陆