How does delegate.Invoke work?

2019-02-08 21:55发布

问题:

If I create a delegate in my code like :

delegate void dostuff (string o);

This generates a class that derives from System.MulticastDelegate which implements three methods - Invoke, BeginInvoke and EndInvoke.

If I look at the compiled IL for Invoke all I see is :

.method public hidebysig newslot virtual 
        instance void  Invoke(string o) runtime managed
{
} // end of method dostuff::Invoke

The method contains no code. Calling it does work - the delegate gets invoked, but I can't see how it does it.

Where does the voodoo that makes calling Invoke actually call the delegate come from?

回答1:

The voodoo can be found at the end of the signature: runtime managed. Notice that all of your managed classes and methods that you define will be decorated as cli managed.

runtime managed means that the runtime provides pre-optimized implementations of the methods.