什么是回调方法? [英] What are callback methods?

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

问题描述

我是一个编程noob,不太理解回调方法背后的概念。试着在维基阅读它,它走过了我的头。可以有人请简单地解释这个吗?

I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?

推荐答案

回调是你传递给函数的东西,它告诉它应该在其操作的某个时刻调用什么。函数中的代码决定何时调用函数(以及传递什么参数)。通常,您执行此操作的方式是将函数本身传递为回调,在函数是对象的语言中。在其他语言中,你可能需要传递一些被称为函数指针(或类似的)的特殊东西。或者您可能必须传递函数的名称(然后在运行时查找)。

The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).

在Python中一个简单的例子:

A trivial example, in Python:

void call_something_three_times(what_to_call, what_to_pass_it):
    for i in xrange(3): what_to_call(what_to_pass_it)

# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")

示例让我们将重复一个函数调用的任务与实际调用该函数的任务分开。这不是很有用,但它演示的概念。

This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.

在现实世界中,回调被用于很多东西像线程库,你调用一些线程创建函数有一个回调描述线程将做的工作。线程创建函数做必要的工作来设置线程,然后安排回调函数被新线程调用。

In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.

这篇关于什么是回调方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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