2015-06-14 82 views
3

假設我有在C#中的一些代表:C#委託:字面構造

public delegate void ExampleDelegate(); 

和地方我有SampleMethod,我想委託引用:

ExampleDelegate sample = new ExampleDelegate(SampleMethod); 

我見過一些人做在2行,而不是這樣的:

ExampleDelegate sample; 
sample = SampleMethod; 

這是像上面的行功能相同或是有一些(意外的)副作用正在進行?基本上,我不明白之間的差別:

ExampleDelegate sample = new ExampleDelegate(SampleMethod); 

ExampleDelegate sample; = SampleMethod; 

他們似乎工作的同..

+5

查找_method組conversion_ – chomba

回答

2

他們沒有區別他們產生完全相同的CIL代碼。

例如。給出下面的C#代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication6 
{ 
    public delegate void ExampleDelegate(); 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ExampleDelegate sample1 = new ExampleDelegate(SampleMethod); 
      ExampleDelegate sample2 = SampleMethod; 
     } 

     static void SampleMethod() 
     { 

     } 
    } 
} 

這是主要的方法的CIL代碼:

.method private hidebysig static void Main(string[] args) cil managed 
{ 
    .entrypoint 
    // Code size  28 (0x1c) 
    .maxstack 2 
    .locals init ([0] class ConsoleApplication6.ExampleDelegate sample1, 
      [1] class ConsoleApplication6.ExampleDelegate sample2) 
    IL_0000: nop 
    IL_0001: ldnull 
    IL_0002: ldftn  void ConsoleApplication6.Program::SampleMethod() 
    IL_0008: newobj  instance void ConsoleApplication6.ExampleDelegate::.ctor(object, 
                       native int) 
    IL_000d: stloc.0 
    IL_000e: ldnull 
    IL_000f: ldftn  void ConsoleApplication6.Program::SampleMethod() 
    IL_0015: newobj  instance void ConsoleApplication6.ExampleDelegate::.ctor(object, 
                       native int) 
    IL_001a: stloc.1 
    IL_001b: ret 
} // end of method Program::Main