C# 委托和回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1746332/
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
Delegates and Callbacks
提问by user160677
Does the term callback in the context of delegates mean ,"a delegate delegating it works to another delegate inorder to finish some task" ?
委托上下文中的术语回调是否意味着“一个委托将它委托给另一个委托以完成某些任务”?
Example :(Based on my understanding,I have implemented a callback,correct me if it is wrong)
示例:(根据我的理解,我已经实现了回调,如果有误请纠正我)
namespace Test
{
public delegate string CallbackDemo(string str);
class Program
{
static void Main(string[] args)
{
CallbackDemo handler = new CallbackDemo(StrAnother);
string substr = Strfunc(handler);
Console.WriteLine(substr);
Console.ReadKey(true);
}
static string Strfunc(CallbackDemo callback)
{
return callback("Hello World");
}
static string StrAnother(string str)
{
return str.Substring(1, 3).ToString();
}
}
}
Please provide examples as necessary.
请根据需要提供示例。
采纳答案by RCIX
Your example is a good start, but it is incorrect. You don't make a new delegate in the method, it's used in the declaration of an event in the class. See this modified example of your code:
你的例子是一个好的开始,但它是不正确的。您不会在方法中创建新委托,而是在类中的事件声明中使用它。请参阅此修改后的代码示例:
namespace Test
{
//In this case, this delegate declaration is like specifying a specific kind of function that must be used with events.
public delegate string CallbackDemo(string str);
class Program
{
public static event CallbackDemo OnFoobared;
static void Main(string[] args)
{
//this means that StrAnother is "subscribing" to the event, in other words it gets called when the event is fired
OnFoobared += StrAnother;
string substr = Strfunc();
Console.WriteLine(substr);
Console.ReadKey(true);
//this is the other use of delegates, in this case they are being used as an "anonymous function".
//This one takes no parameters and returns void, and it's equivalent to the function declaration
//'void myMethod() { Console.WriteLine("another use of a delegate"); }'
Action myCode = delegate
{
Console.WriteLine("another use of a delegate");
};
myCode();
Console.ReadKey(true);
//the previous 4 lines are equivalent to the following however this is generally what you should use if you can
//its called a lambda expression but it's basically a way to toss arbitrary code around
//read more at http://www.developer.com/net/csharp/article.php/3598381/The-New-Lambda-Expressions-Feature-in-C-30.htm or
//http://stackoverflow.com/questions/167343/c-lambda-expression-why-should-i-use-this
Action myCode2 = () => Console.WriteLine("a lambda expression");
myCode2();
Console.ReadKey(true);
}
static string Strfunc()
{
return OnFoobared("a use of a delegate (with an event)");
}
static string StrAnother(string str)
{
return str.Substring(1, 3).ToString();
}
}
}
I've only scratched the surface here; search stack overflow for "delegate c#" and "lambda expression c#" for lots more!
我只是触及了表面;搜索“delegate c#”和“lambda expression c#”的堆栈溢出以获取更多信息!
回答by itowlson
A callback is basically a delegate passed into a procedure which that procedure will "call back" at some appropriate point. For example, in asynchronous calls such as WebRequest.BeginGetResponse or a WCF BeginXxx operation, you'd pass an AsyncCallback. The worker will "call back" whatever method you pass in as the AsyncCallback, in this case when it's finished to let you know that it's finished and to obtain the result.
回调基本上是传递给过程的委托,该过程将在某个适当的点“回调”。例如,在诸如 WebRequest.BeginGetResponse 或 WCF BeginXxx 操作之类的异步调用中,您需要传递一个 AsyncCallback。工作人员将“回调”您作为 AsyncCallback 传入的任何方法,在这种情况下,当它完成时让您知道它已完成并获得结果。
An event handler could be considered another example. For example, when you attach a handler to a Click event, the button will "call back" to that handler when the click occurs.
可以将事件处理程序视为另一个示例。例如,当您将处理程序附加到 Click 事件时,按钮将在发生单击时“回调”到该处理程序。
回答by itowlson
A callback is what the delegate executes when it is invoked. For example, when using the Asynchronous pattern using delegates, you would do something like this:
回调是委托在调用时执行的操作。例如,在使用委托的异步模式时,您将执行以下操作:
public static void Main(string[] args)
{
Socket s = new Socket(...);
byte[] buffer = new byte[10];
s.BeginReceive(buffer, 0, 10, SocketFlags.None, new AsyncCallback(OnMessageReceived), buffer);
Console.ReadKey();
}
public static void OnMessageReceived(IAsyncResult result)
{
// ...
}
OnMessageReceived
is the callback, the code that is executed by invoking the delegate. See this Wikipedia articlefor some more information, or Google some more examples.
OnMessageReceived
是回调,通过调用委托执行的代码。有关更多信息,请参阅此 Wikipedia 文章,或谷歌更多示例。
回答by Lloyd Sargent
This will get down voted precisely for the reason it is correct. C# does not implement delegates, what it implements is call forwarding. This incorrect use of nomenclature is probably the biggest problem with C# in this regard.
这将因为它是正确的原因而被否决。C# 没有实现委托,它实现的是呼叫转发。这种对命名法的错误使用可能是 C# 在这方面的最大问题。
The ACM paper below is the first description of what later would be called a delegate. Basically a delegate is something that appears to be an instance of an object (how it is actually implemented is irrelevant). This means that you can call methods, access properties, etc. from the delegate.
下面的 ACM 论文是对后来被称为委托的第一个描述。基本上,委托是看起来是对象实例的东西(它的实际实现方式无关紧要)。这意味着您可以从委托调用方法、访问属性等。
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html
What C# implements is callbacks or call-forwarding (all dependent on how you use them). These are not delegates. In order to be a delegate one be able to access the object as if it were the object itself.
C# 实现的是回调或呼叫转发(都取决于您如何使用它们)。这些不是代表。为了成为委托人,可以像访问对象本身一样访问对象。
When a pen delegates a draw message to a prototypical pen, it is saying “I don't know how to handle the draw message. I'd like you to answer it for me if you can, but if you have any further questions, like what is the value of my x variable, or need anything done, you should come back to me and ask.” If the message is delegated further, all questions about the values of variables or requests to reply to messages are all inferred to the object that delegated the message in the first place. - Henry Lieberman
当笔将绘图消息委托给原型笔时,它表示“我不知道如何处理绘图消息。如果可以,我希望你为我回答,但如果你有任何进一步的问题,比如我的 x 变量的值是什么,或者需要做任何事情,你应该回来问我。” 如果消息被进一步委托,所有关于变量值的问题或回复消息的请求都被推断为首先委托消息的对象。——亨利·利伯曼
So, how did it get messed up? To be honest, I don't know. I DO know that I've been using delegates (over 16 years now) long before C# and what C# implements are not delegates.
那么,它是怎么搞砸的呢?老实说,我不知道。我知道我早在 C# 之前就一直在使用委托(现在已经超过 16 年了)并且 C# 实现的不是委托。
A really good explanation can be had here.
这里可以有一个非常好的解释。
Real delegation is more than creating callbacks or call forwarding. A real delegate lets me call any method on that object, get and/or set public properties, etc - all as if it was the object itself. This is far more powerful, and actually easier to use, than the C# "delegation".
真正的委托不仅仅是创建回调或呼叫转移。真正的委托让我可以调用该对象上的任何方法,获取和/或设置公共属性等 - 就好像它是对象本身一样。这比 C# 的“委托”功能强大得多,实际上也更易于使用。
The OP asked:
OP问:
Does the term callback in the context of delegates mean ,"a delegate delegating it works to another delegate inorder to finish some task" ?
委托上下文中的术语回调是否意味着“一个委托将它委托给另一个委托以完成某些任务”?
The answer to this is yes. A callback in the context of delegates can can only beused to finish up some task. For example, you have a class that get's data from a weather site. Since it is non-deterministic, implementing a callback when the data has been received (and perhaps parsed) would be spiffy.
答案是肯定的。委托上下文中的回调只能用于完成某些任务。例如,您有一个从天气站点获取数据的类。由于它是非确定性的,因此在接收到(并且可能已解析)数据时实现回调将是非常好的。
As to why delegation was corrupted, I've no idea. I look forward to C# implementing TRUE delegation.
至于为什么代表团被破坏,我不知道。我期待 C# 实现 TRUE 委托。