c# - Any difference is there Invoke Method (Delegate) and direct call? -
this question has answer here:
may question asked earlier ,i did googling didnt answer.
delegate prototype
delegate void method1(string str);
adding callback methods
method1 objdel2; objdel2 = new method1(testmethod1); objdel2("test"); objdel2.invoke("invoke");
in above coding objdel2("test");
, objdel2.invoke("invoke");
doing same task.which 1 or both same .
they 100% identical - pure compiler sugar (see below). preferred: neither / both.
static class program { static void main() { method1 objdel2; objdel2 = new method1(testmethod1); objdel2("test"); objdel2.invoke("invoke"); } delegate void method1(string val); static void testmethod1(string val) { system.console.writeline(val); } }
has il
.method private hidebysig static void main() cil managed { .entrypoint .maxstack 2 .locals init ( [0] class program/method1 'method') l_0000: ldnull l_0001: ldftn void program::testmethod1(string) l_0007: newobj instance void program/method1::.ctor(object, native int) l_000c: stloc.0 l_000d: ldloc.0 l_000e: ldstr "test" l_0013: callvirt instance void program/method1::invoke(string) ***here*** l_0018: ldloc.0 l_0019: ldstr "invoke" l_001e: callvirt instance void program/method1::invoke(string) ***here*** l_0023: ret }
note both same thing (see 2 locations marked me ***here***
)
Comments
Post a Comment