How delegates work (in the background)?

前端 未结 6 578
温柔的废话
温柔的废话 2020-12-10 06:16

How do delegates work in c# behind the scenes and how can they be used efficiently?

EDIT: I know how they work on the surface(they are basically function pointers a

6条回答
  •  不知归路
    2020-12-10 06:45

    When you define your delegate

    internal delegate void Feedback(Int32 value);
    

    the compiler actually defines a complete class that looks something like this:

    internal class Feedback : System.MulticastDelegate {  
       // Constructor  
       public Feedback(Object object, IntPtr method);  
    
       // Method with same prototype as specified by the source code  
       public virtual void Invoke(Int32 value);  
    
       // Methods allowing the callback to be called asynchronously  
       public virtual IAsyncResult BeginInvoke(Int32 value,  AsyncCallback callback, Object object);  
    
       public virtual void EndInvoke(IAsyncResult result);  
    }
    

    Source: Jeffrey Richter - CLR via C#, chapter 17

提交回复
热议问题