How delegates work (in the background)?

前端 未结 6 569
温柔的废话
温柔的废话 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 07:04

    C# delegates are objects (check the System.Delegate class) that encapsulate a reference to an object and a method pointer. They can also have a null reference to object to represent a call to a static method.

    When invoking the delegate with arguments, the delegate crafts a call to the referenced method on referenced object with specified arguments.

    A compiled delegate Invoke method is directly handled by the runtime (as visible with Reflector):

    [MethodImpl(0, MethodCodeType=MethodCodeType.Runtime)]
    public virtual void Invoke(T obj);
    

    The runtime use all the info internaly to compile a standard method call to the referenced method.

提交回复
热议问题