开发者

Compiler treatment of a Delegate

开发者 https://www.devze.com 2022-12-12 04:14 出处:网络
If i declare a delegate public delegate void firstDelegate(string str); firstDelegate handler = Strfunc;

If i declare a delegate

public delegate void firstDelegate(string str);

firstDelegate handler = Strfunc;

handler("Hello World");

  ..
  static void Strfunc(string str)
  {
        Console.WriteLine(str);
  }

will the compiler translate the following line

firstDelegate handler=S开发者_如何转开发trfunc;

into

firstDelegate=new firstDelegate(Strfunc);


That's right. Here is the disassembly from reflector:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 3
    .locals init (
        [0] class ConsoleApplication4.Program/firstDelegate handler)
    L_0000: nop 
    L_0001: ldnull 
    L_0002: ldftn void ConsoleApplication4.Program::Strfunc(string)
    L_0008: newobj instance void ConsoleApplication4.Program/firstDelegate::.ctor(object, native int)
    L_000d: stloc.0 
    L_000e: ldloc.0 
    L_000f: ldstr "Hello World"
    L_0014: callvirt instance void ConsoleApplication4.Program/firstDelegate::Invoke(string)
    L_0019: nop 
    L_001a: ret 
}

which looks like this in C#:

private static void Main(string[] args)
{
    firstDelegate handler = new firstDelegate(Program.Strfunc);
    handler("Hello World");
}


So far I can tell, YES.

This is called as "delegate inference".

BTW, if you want to "append" another function to this delegate, use:

handler += AnotherFunctionName;

And here is the words from C# Pros in the book professional-C#-2008, chapter 7:

For less typing, at every place where a delegate instance is needed, you can just pass the name of the address. This is known by the term delegate inference. This C# feature works as long as the compiler can resolve the delegate instance to a specific type. The code that is created by the C# compiler is the same. The compiler detects that a delegate type is required, so it creates an instance of that delegate type and passes the address of the method to the constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号