C# 什么是回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2139812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:50:33  来源:igfitidea点击:

What is a callback?

c#callback

提问by cam

What's a callback and how is it implemented in C#?

什么是回调,它是如何在 C# 中实现的?

采纳答案by Joey

In computer programming, a callback is executable codethat is passed as an argumentto other code.

Wikipedia: Callback (computer science)

计算机编程中,回调是作为参数传递给其他代码的可执行代码。

维基百科:回调(计算机科学)

C# has delegatesfor that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

C# 具有用于此目的的委托。它们与events大量使用,因为事件可以自动调用许多附加的委托(事件处理程序)。

回答by Zyphrax

If you referring to ASP.Net callbacks:

如果您指的是 ASP.Net 回调:

In the default model for ASP.NET Web pages, the user interacts with a page and clicks a button or performs some other action that results in a postback. The page and its controls are re-created, the page code runs on the server, and a new version of the page is rendered to the browser. However, in some situations, it is useful to run server code from the client without performing a postback. If the client script in the page is maintaining some state information (for example, local variable values), posting the page and getting a new copy of it destroys that state. Additionally, page postbacks introduce processing overhead that can decrease performance and force the user to wait for the page to be processed and re-created.

To avoid losing client state and not incur the processing overhead of a server roundtrip, you can code an ASP.NET Web page so that it can perform client callbacks. In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.

在 ASP.NET 网页的默认模型中,用户与页面交互并单击按钮或执行导致回发的某些其他操作。重新创建页面及其控件,在服务器上运行页面代码,并将页面的新版本呈现给浏览器。但是,在某些情况下,从客户端运行服务器代码而不执行回发会很有用。如果页面中的客户端脚本正在维护一些状态信息(例如,局部变量值),则发布页面并获取它的新副本会破坏该状态。此外,页面回发会引入处理开销,这会降低性能并迫使用户等待页面被处理和重新创建。

为了避免丢失客户端状态并且不会产生服务器往返的处理开销,您可以编写一个 ASP.NET 网页,以便它可以执行客户端回调。在客户端回调中,客户端脚本函数向 ASP.NET 网页发送请求。网页运行其正常生命周期的修改版本。启动页面并创建其控件和其他成员,然后调用一个特别标记的方法。该方法执行您编码的处理,然后将一个值返回给浏览器,该值可由另一个客户端脚本函数读取。在整个过程中,页面都在浏览器中。

Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx

来源:http: //msdn.microsoft.com/en-us/library/ms178208.aspx

If you are referring to callbacks in code:

如果您指的是代码中的回调:

Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.

回调通常是对特定操作完成或执行子操作时调用的方法的委托。您经常会在异步操作中找到它们。这是几乎在每种编码语言中都可以找到的编程原则。

More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx

更多信息:http: //msdn.microsoft.com/en-us/library/ms173172.aspx

回答by TLiebe

A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.

回调是您传递给另一个函数的函数指针。您正在调用的函数将在完成后“回调”(执行)另一个函数。

Check out thislink.

看看这个链接。

回答by David

A callback lets you pass executable code as an argument to other code. In C and C++ this is implemented as a function pointer. In .NET you would use a delegate to manage function pointers.

回调允许您将可执行代码作为参数传递给其他代码。在 C 和 C++ 中,这是作为函数指针实现的。在 .NET 中,您将使用委托来管理函数指针。

A few uses include error signaling and controlling whether a function acts or not.

一些用途包括错误信号和控制函数是否起作用。

Wikipedia

维基百科

回答by serhio

Definition

定义

A callbackis executable code that is passed as an argument to other code.

一个回调是作为参数传递给其他代码通过可执行代码。

Implementation

执行

// Parent can Read
public class Parent
{
    public string Read(){ /*reads here*/ };
}

// Child need Info
public class Child
{
    private string information;
    // declare a Delegate
    delegate string GetInfo();
    // use an instance of the declared Delegate
    public GetInfo GetMeInformation;

    public void ObtainInfo()
    {
        // Child will use the Parent capabilities via the Delegate
        information = GetMeInformation();
    }
}

Usage

用法

Parent Peter = new Parent();
Child Johny = new Child();

// Tell Johny from where to obtain info
Johny.GetMeInformation = Peter.Read;

Johny.ObtainInfo(); // here Johny 'asks' Peter to read

Links

链接

回答by Antony Woods

Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.

可能不是字典定义,但回调通常指的是一个函数,它位于特定对象的外部,被存储然后在特定事件上调用。

An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.

例如,当创建 UI 按钮时,它会存储对执行操作的函数的引用。该动作由代码的不同部分处理,但是当按下按钮时,将调用回调并调用要执行的动作。

C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.

C#,而不是使用术语“回调”使用“事件”和“委托”,您可以在此处找到有关委托的更多信息。

回答by Pierre-Alain Vigeant

A callback is a function that will be called when a process is done executing a specific task.

回调是一个函数,当进程完成执行特定任务时将调用该函数。

The usage of a callback is usually in asynchronous logic.

回调的使用通常在异步逻辑中。

To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegateor the new lambda semantic Funcor Action.

要在 C# 中创建回调,您需要将函数地址存储在变量中。这是使用 adelegate或新的 lambda 语义Funcor 来实现的Action

    public delegate void WorkCompletedCallBack(string result);

    public void DoWork(WorkCompletedCallBack callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
        DoWork(callback);
    }

    public void TestCallBack(string result)
    {
        Console.WriteLine(result);
    }

In today C#, this could be done using lambda like:

在今天的 C# 中,这可以使用 lambda 来完成,例如:

    public void DoWork(Action<string> callback)
    {
        callback("Hello world");
    }

    public void Test()
    {
        DoWork((result) => Console.WriteLine(result));
    }

回答by Ganesha

callback work steps:

回调工作步骤:

1) we have to implement ICallbackEventHandlerInterface

1)我们必须实现ICallbackEventHandler接口

2) Register the client script :

2)注册客户端脚本:

 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
    String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);

1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)

1) 从 UI 调用 Onclient 单击调用 EX 的 javascript 函数:- builpopup(p1,p2,p3...)

var finalfield= p1,p2,p3; UseCallBack(finalfield, "");data from the client passed to server side by using UseCallBack

var finalfield= p1,p2,p3; UseCallBack(finalfield, "");来自客户端的数据通过 UseCallBack 传递给服务器端

2) public void RaiseCallbackEvent(string eventArgument)In eventArgument we get the passed data //do some server side operation and passed to "callbackResult"

2) public void RaiseCallbackEvent(string eventArgument)在 eventArgument 中我们得到传递的数据 // 做一些服务器端操作并传递给“callbackResult”

3) GetCallbackResult()// using this method data will be passed to client(ReceiveServerData() function) side

3) GetCallbackResult()// 使用此方法数据将被传递到客户端(ReceiveServerData() 函数)端

callbackResult

回调结果

4) Get the data at client side: ReceiveServerData(text), in text server response , we wil get.

4)在客户端获取数据: ReceiveServerData(text),在文本服务器响应中,我们将得到。

回答by LightStriker

I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?

我刚认识你,
这太疯狂了,
但这是我的号码(代表),
所以如果发生什么事(事件),
给我打电话,也许(回电)?

回答by Mani

Dedication to LightStriker:
Sample Code:

献给 LightStriker:
示例代码:

class CallBackExample
{
    public delegate void MyNumber();
    public static void CallMeBack()
    {
        Console.WriteLine("He/She is calling you.  Pick your phone!:)");
        Console.Read();
    }
    public static void MetYourCrush(MyNumber number)
    {
        int j;
        Console.WriteLine("is she/he interested 0/1?:");
        var i = Console.ReadLine();
        if (int.TryParse(i, out j))
        {
            var interested = (j == 0) ? false : true;
            if (interested)//event
            {
                //call his/her number
                number();
            }
            else
            {
                Console.WriteLine("Nothing happened! :(");
                Console.Read();
            }
        }
    }
    static void Main(string[] args)
    {
        MyNumber number = Program.CallMeBack;
        Console.WriteLine("You have just met your crush and given your number");
        MetYourCrush(number);
        Console.Read();
        Console.Read();
    }       
}

Code Explanation:

代码说明:

I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBackmethod. So, the CallMeBackmethod will be called. Basically, we are passing delegate to call the callback method.

我创建了代码来实现 LightStriker 在上述回复中提供的有趣解释。我们将委托(编号)传递给方法 ( MetYourCrush)。如果兴趣(事件)发生在方法 ( MetYourCrush) 中,那么它将调用持有CallMeBack方法引用的委托(编号)。因此,该CallMeBack方法将被调用。基本上,我们通过委托来调用回调方法。

Please let me know if you have any questions.

请让我知道,如果你有任何问题。