简体   繁体   English

代表如何指向方法?

[英]How can delegates point to methods?

In C# we have value types and reference types. 在C#中,我们有值类型和引用类型。 I understand pretty well some code like 我很了解一些代码,例如

public class Employee
{
   // Code for Employee goes here 
}

public class Program
{
     public void Main(string[] args)
     {
          Employee someEmployee;
          someEmployee = new Employee();
          // Do something with someEmployee
     }
}

When we do Employee someEmployee; 当我们做Employee时,某些雇员; the runtime allocates memory on the stack sufficient to hold the address of a piece of the heap that holds data for an Employee. 运行时会在堆栈上分配足够的内存,以容纳用于保存Employee数据的一部分堆的地址。 The line someEmployee = new Employee(); 该行someEmployee = new Employee(); then allocates memory on the heap, initializes what is needed and at the end puts the address on the variable someEmployee. 然后在堆上分配内存,初始化所需的内容,最后将地址放入变量some​​Employee。

What goes on the heap is then the data that an Employee has. 然后,堆中的内容就是一个雇员拥有的数据 It is easy to grasp that someEmployee holds a reference to a piece of the memory that has data on it as we are used to see. 就像我们过去经常看到的那样,不难理解someEmployee拥有对内存中有数据的引用。

Now, a delegate points to a method. 现在,一个委托指向一个方法。 But what does this means? 但这意味着什么? What should mean point to a method? 指一种方法意味着什么? A method is saved in the heap like other data? 方法是否像其他数据一样保存在堆中? This confuses me because a method is not just a bunch of data, it is a bunch of instructions, so what should mean to store instructions? 这使我感到困惑,因为方法不仅是一堆数据,而是一堆指令,那么存储指令应该是什么意思?

You can think of a delegate as something like this 您可以将代表视为这样

public class Action : Delegate
{
    private object instance;
    private MethodInfo method;
    public void Invoke()
    {
        method.Invoke(instance, new object[]{});
    }
}

Now, obviously, this isn't exactly what that will look like, and there is a lot of syntactic sugar and direct runtime support, etc., but this should give you some sort of idea as to what's going on. 现在,显然,这并不完全是这样,并且有很多语法糖和直接的运行时支持等,但这应该使您对发生的事情有所了解。 A delegate is just a type, much like a class. 委托只是一个类型,很像一个类。 It will result in memory allocations on the heap to represent a method and an (optional) instance to call it on, and the variables typed as a delegate hold references to this object. 这将导致在堆上分配内存,以表示一个方法和一个调用它的(可选)实例,并且键入为委托的变量将保留对此对象的引用。

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

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