/*
Delegates implement callbacks: the mechanism of
passing callbacks with methods as parameters through delegates
: from calling side -> definition side -> calling side -> definition side -> calling side
The caller executes the method (the method parameter contains the entrusted type) ->
enters the definition method port, executes the code block in the method, executes to the entrusted method ->
returns to the caller to execute the passed method parameter ->
returns to the definition end and continues to execute The code block ->
return to the caller after execution
*/
class TestCallBack
{ TesHandler handler =new TesHandler(); //1. Execute the method (assuming the method is the entry point, execute the method) public void DebugResult() { //2. Then execute the method handler.Result(3, 2 , (a,b)=>{return a+b;});//5. Go back to the caller and execute (a,b)=>{return a+b;} }//8. Exit the caller method }
class TesHandler
{ //3. Enter Result public int Result(int a, int b , CalTestHandler calHandler ) { //4. Call the delegate method return calHandler(a, b);//6. Return to the definition end and execute it }/ /7. Exit definition end method
//Define delegate
public delegate int CalTestHandler(int a, int b);
}
/*
委托实现回调:
通过委托以方法作为参数进行传递
回调的机制:从调用端 -> 定义端 -> 调用端 -> 定义端 -> 调用端
调用端 执行方法(方法参数含有委托类型) ->
进入到定义方法端口,执行方法中的代码块,执行到委托方法 ->
回到调用端执行传递的方法参数 ->
回到定义端 继续执行后面的代码块 ->
执行完毕 回到调用端
*/
class TestCallBack
{
TesHandler handler =new TesHandler();
//1.执行该方法(假设该方法为入口 即执行该方法)
public void DebugResult()
{
//2.进而执行该方法
handler.Result(3, 2, (a,b)=>{return a+b;});//5.回到调用端 执行(a,b)=>{return a+b;}
}//8.退出调用端方法
}
class TesHandler
{
//3.进入Result
public int Result(int a, int b , CalTestHandler calHandler )
{
//4.调用委托方法
return calHandler(a, b);//6.回到定义端 执行完毕
}//7.退出定义端方法
//定义委托
public delegate int CalTestHandler(int a, int b);
}