Delegates and Callbacks

后端 未结 4 945
有刺的猬
有刺的猬 2021-02-03 14:07

Does the term callback in the context of delegates mean ,\"a delegate delegating it works to another delegate inorder to finish some task\" ?

Example :(

4条回答
  •  孤街浪徒
    2021-02-03 14:21

    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.

    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.

    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.

    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

    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.

    A really good explanation can be had here.

    http://www.saturnflyer.com/blog/jim/2012/07/06/the-gang-of-four-is-wrong-and-you-dont-understand-delegation/

    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".

    The OP asked:

    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 be used 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.

提交回复
热议问题