简体   繁体   English

如何将实例方法转换为委托?

[英]How are instance methods converted to delegates?

It seems simple enough how static methods are invoked in delegates, as all of their parameters will be passed to them when the delegate itself is invoked. 在委托中调用静态方法似乎很简单,因为在调用委托本身时,它们的所有参数都将传递给它们。
However when an instance method is added to a delegate, the 'this' parameter is seemingly ignored during the invocation of the delegate, and so I can only imagine that it is saved alongside the delegate itself - similar to what a closure can do with other parameters. 但是,当一个实例方法被添加到委托时,'this'参数在调用委托期间似乎被忽略了,所以我只能想象它与委托本身一起保存 - 类似于一个闭包可以用于其他参数。

Q: Will a closure be created by the compiler when an instance method is passed to a delegate, or is there a different mechanism by which this is accomplished? 问:当实例方法传递给委托时,编译器是否会创建闭包,或者是否有不同的机制来完成此操作?

No. 没有。

The Delegate class has a Target property which stores the value of this to pass when calling the method. Delegate类有一个Target存储的值属性this调用该方法时通过。
In other words, a Delegate actually stores two things: A function pointer and a value for the first parameter. 换句话说, Delegate实际上存储了件事:一个函数指针和第一个参数的值。

A delegate that contains a target is called a closed delegate , since it closes over the first parameter. 包含目标的委托称为封闭委托 ,因为它会关闭第一个参数。

In fact, this is actually, how closures work. 实际上,这实际上就是闭包的工作方式。 When the compiler creates a closure for a delegate, it will create a class that holds the variables that are closed over, and store that class as the delegate's Target . 当编译器为委托创建闭包时,它将创建一个包含已关闭的变量的类,并将该类存储为委托的Target

For more information, see my blog posts: 有关更多信息,请参阅我的博文:

Have a look at the (underlying) Delegate class. 看看(底层)Delegate类。 It defines a member called Target which defines the instance. 它定义了一个名为Target的成员,用于定义实例。 In case of a static method Target is associated with the class itself. 在静态方法的情况下, Target与类本身相关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM