什么是回调?

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

288301 次浏览

如果您指的是ASP。净回调函数:

在ASP. ASP. 0的默认模型中。网网络 页面,用户与页面交互 然后点击一个按钮或执行一些操作 导致事件的其他操作 回发。页面及其控件 重新创建,页面代码运行 服务器端,以及新版本的 页面呈现给浏览器。 然而,在某些情况下,确实如此 中运行服务器代码非常有用 客户端不执行回发。 如果页面中的客户端脚本为 维护一些状态信息 (例如,局部变量值), 发布页面并获得新的 复制它会破坏这种状态。 此外,页面回发引入 处理开销可以减少 性能和强制用户等待 用于要处理的页面 重新创建. < / p >

避免丢失客户端状态 的处理开销 服务器往返,您可以编写一个 ASP。NET Web页面,以便它可以 执行客户端回调。在客户端中 Callback,一个客户端-脚本函数 发送一个请求到ASP。网网络 页面。Web页面运行已修改的 版本的正常生命周期。的 页及其控件和 创建其他成员,然后a 调用特殊标记的方法。 该方法执行处理 然后返回一个 可以读取的浏览器的值 由另一个客户端脚本函数。 在整个过程中,页面是

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

如果你在代码中引用回调:

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

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

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

查看链接。

计算机编程中,回调是可执行代码,它作为论点传递给其他代码。

-Wikipedia: Callback(计算机科学)

c#有代表用于此目的。它们在事件中大量使用,因为一个事件可以自动调用许多附加的委托(事件处理程序)。

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

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

Wikipedia

定义

A 回调是可执行代码 作为参数传递给其他代码。< / p >

实现

// 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();
}
}

使用

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

链接

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

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

c#,而不是使用术语'回调'使用'事件'和'委托',你可以找到更多关于委托在这里

回调函数是在流程执行完特定任务时调用的函数。

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

要在c#中创建回调,需要在变量中存储函数地址。这是使用delegate或新的lambda语义FuncAction来实现的。

    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);
}

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

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


public void Test()
{
DoWork((result) => Console.WriteLine(result));
DoWork(Console.WriteLine); // This also works
}

回调工作步骤:

1)我们必须实现ICallbackEventHandler接口

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)从UI调用在客户端点击调用javascript功能的EX:- builpopup(p1,p2,p3...)

var finalfield= p1,p2,p3; UseCallBack(finalfield, "");数据从客户端传递到服务器端使用UseCallBack

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

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

callbackResult

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

我才刚认识你,
这太疯狂了,
这里是我的number (delegate)
如果有事情发生(event),
打给我吧(回电话)?< / p >

献给LightStriker:
示例代码:< / p >

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();
}
}

代码的解释:

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

如果你有任何问题,请告诉我。

回调是作为参数传递给另一个函数的函数。这种技术允许函数调用形参函数实参,甚至将值传递回调用方。回调函数可以设计为在函数结束之前/之后运行,并且可以传递一个值。

它是一种构造,你调用一个长时间运行的函数,并要求他在它完成后回调你,可以返回一个参数结果给调用者。

一个简单的例子是迭代器函数,其返回值将是多次,可以认为我们为它设置了yield:

public void IntreationLoop(int min, int max,Action<int> Callback)
{
for(int i = min;i<= max;i++)
Callback(i);
}


//call
IntreationLoop(5,50,(x) => { Console.Write(x); }); //will print 5-50 numbers

在上面的代码中,函数返回类型是void,但它有一个Action<int>回调函数,该回调函数被调用并将循环中的每个项发送给调用者。

同样的事情也可以用if..elsetry..catch块完成:

public void TryCatch(Action tryFor,Action catchIt)
{
try{
tryFor();
}
catch(Exception ex)
{
Console.WriteLine($"[{ex.HResult}] {ex.Message}");
catchIt();
}
}

称之为:

TryCatch(()=>{
int r = 44;
Console.WriteLine("Throwing Exception");
throw new Exception("something is wrong here");
}, ()=>{
Console.WriteLine("It was a mistake, will not try again");
});

在2022年,我们有Func &Action做同样的事情,请参阅下面的演示代码,其中展示了如何使用它:

void Main()
{
var demo = new CallbackDemo();
demo.DoWork(()=> { Console.WriteLine("I have finished the work"); });
demo.DoWork((r)=> { Console.WriteLine($"I have finished the work here is the result {r}"); });
demo.DoWork(()=> { Console.WriteLine($"This is passed with func"); return 5;});
demo.DoWork((f)=> { Console.WriteLine($"This is passed with func and result is {f}"); return 10;});
    

}


// Define other methods and classes here
public class CallbackDemo
{


public void DoWork(Action actionNoParameter)
{
int a = 5;
int b = 10;
        

//i will do th maths and call you back
int result = a + b;
        

//callback
actionNoParameter(); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
    

public void DoWork(Action<int> actionWithParameter)
{
int a = 5;
int b = 10;
        

//i will do th maths and call you back
int result = a + b;
        

//callback
actionWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
    

public void DoWork(Func<int> funcWithReturn)
{
int a = 5;
int b = 10;
        

//i will do th maths and call you back
int result = a + b;
        

//callback
int c = funcWithReturn(); //execute
        

result += c;
Console.WriteLine($"[The Actual Result is {result}]");
}
    

public void DoWork(Func<int,int> funcWithParameter)
{
int a = 5;
int b = 10;
        

//i will do th maths and call you back
int result = a + b;
        

//callback
result += funcWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
}