简体   繁体   中英

How can delegates point to methods?

In C# we have value types and reference types. 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; the runtime allocates memory on the stack sufficient to hold the address of a piece of the heap that holds data for an Employee. The line someEmployee = new Employee(); then allocates memory on the heap, initializes what is needed and at the end puts the address on the variable someEmployee.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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