什么是回调,它在c#中是如何实现的?
当前回答
定义
回调是可执行的代码 作为参数传递给其他代码。
实现
// 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
链接
c#的更多细节。
其他回答
回调是作为参数传递给另一个函数的函数。这种技术允许函数调用形参函数实参,甚至将值传递回调用方。回调函数可以设计为在函数结束之前/之后运行,并且可以传递一个值。
它是一种构造,你调用一个长时间运行的函数,并要求他在它完成后回调你,可以返回一个参数结果给调用者。
这就像有人在你工作的时候打电话给你询问状态,你说“你知道吗,给我5分钟,我会给你回电”,最后你打电话给他更新情况。如果你是一个函数,调用者只是添加并传递了另一个你在最后调用的函数。这可以简单地用c#编写为:
public void VinodSrivastav(Action statusUpdate){
//i am still here working..working
//i have finished, calling you
statusUpdate();
}
//invokes
stackoverflow.VinodSrivastav((cam) => {
Console.Write("Is it finished");
});
一个简单的例子是迭代器函数,其中的return将是多次,可以认为我们为它设置了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..else或try..catch block as:
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}]");
}
}
对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();
}
}
代码的解释:
我创建了代码来实现LightStriker在上面一个回复中提供的有趣解释。我们正在传递委托(数字)到一个方法(MetYourCrush)。如果感兴趣(事件)发生在方法(MetYourCrush)中,那么它将调用持有CallMeBack方法引用的委托(数字)。CallMeBack方法会被调用。基本上,我们传递委托来调用回调方法。
如果你有任何问题,请告诉我。
我才刚认识你, 这很疯狂, 这是我的number (delegate) 所以如果发生了什么(事件), 打给我吧(回电话)?
回调工作步骤:
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将客户端的数据传递给服务器端
在eventArgument中我们获取传递的数据 //执行一些服务器端操作并传递给"callbackResult"
3) GetCallbackResult() //使用此方法数据将被传递到客户端(ReceiveServerData()函数)端
callbackResult
4)获取客户端数据: ReceiveServerData(text),在文本服务器响应中,我们将得到。
回调函数是在流程执行完特定任务时调用的函数。
回调的使用通常是在异步逻辑中。
要在c#中创建回调,需要在变量中存储函数地址。这是使用委托或新的lambda语义Func或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);
}
在今天的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
}
推荐文章
- 拒绝访问该路径
- Visual Studio - Resx文件默认“内部”为“公共”
- 使用linq转换列表到字典,不用担心重复
- 单元测试:日期时间。现在
- 什么是回调?
- 返回匿名类型的结果?
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行