Home > Net >  C # to entrust to create the Action instance and does not create difference method is called a deleg
C # to entrust to create the Action instance and does not create difference method is called a deleg

Time:11-19

 using System; 
using System.Collections.Generic;
using System.Linq;

The namespace PropertySample
{
Class Program
{
The static void Main (string [] args)
{
The Calculator Calculator=new Calculator ();
The Action action1=calculator. The Report;//
The Action action2=new Action (calculator. Report);//
Action1 ();
Action2 ();
}
}

The class Calculator
{
Public void Report ()
{
Console. WriteLine (" I have 3 methods. ");
}
}
}

Consult program in picture slash the two sentences can achieve the same effect of entrust, but what is the difference between the two words? Thank you

CodePudding user response:

There is no difference, the junction post (of immiscible points, there is no difference, indeed)

CodePudding user response:

No difference with the first line, the second is written before the Action

CodePudding user response:

reference 1st floor wanghui0380 response:
there is no difference, the junction post (of immiscible points, there is no difference, indeed)


I believe you,
But to ask, may safely draw the conclusion that the method is more valuable,

Dotnet has anti editing tools, the use of the tool we can know what the compiler converts c # code into il intermediate code:
. Method private hidebysig static void Main (string [] args) cil managed 
{
The entrypoint
//Code size 41 (0 x29)
. Maxstack 3
The locals init ([0] class [mscorlib] System. The Action action1)
IL_0000: newobj instance void PropertySample. Calculator: : ctor ()
IL_0005: dup
IL_0006: LDFTN instance void PropertySample. Calculator: : Report ()
IL_000c: newobj instance void [mscorlib] System. Action: : ctor (object,
Native int)
IL_0011: stloc. 0
IL_0012: LDFTN instance void PropertySample. Calculator: : Report ()
IL_0018: newobj instance void [mscorlib] System. Action: : ctor (object,
Native int)
IL_001d: ldloc. 0
IL_001e: callvirt instance void [mscorlib] System. Action: : the Invoke ()
IL_0023: callvirt instance void [mscorlib] System. Action: : the Invoke ()
IL_0028: ret
}//end of method Program: : the Main


Where
IL_0006: LDFTN used to get a method Pointers,
IL_000c: newobj constructor calls to Action, to create a delegate,
.
IL_0012: LDFTN used to get a method Pointers,
IL_0018: newobj constructor calls to Action, to create a delegate,
As you can see, the two written in c #, compiled into intermediate code, is the same,
C # compiler relatively close, let us lose less code, action1 create method on the bottom is action2 creation method,

In addition, you can use any decompiler, dotnet own have ildasm. Exe, can be found in the similar to the following path:
C: \ Program Files \ Microsoft SDKs (x86) \ Windows \ v10.0 A 4.8 Tools \ \ bin \ NETFX ildasm. Exe

  •  Tags:  
  • C#
  • Related