C# compiler oddity with delegate constructors

后端 未结 3 1097
孤城傲影
孤城傲影 2020-12-31 16:31

Based on the following question, I found some odd behaviour of the c# compiler.

The following is valid C#:

static void K() {}

static void Main()
{
          


        
3条回答
  •  独厮守ぢ
    2020-12-31 17:00

    • delegate is a class
    • Action delegate has a constructor like so

      public extern Action(object @object, IntPtr method);

    • Since K is a static method there is no need to pass object to inner most action instance as first argument and hence it passes null

    • Since second argument is pointer to function therefore it passes pointer of K method using ldftn function
    • for the remaining Action instances the object is passed is inner Action and the second parameter is the Invoke method since when you call a delegate you're actually calling the Invoke method

    Summary

    var action = new Action(K) => Action action = new Action(null, ldftn(K))
    new Action(action) => new Action(action, ldftn(Action.Invoke))
    

    I hope this explains what is happening?

提交回复
热议问题