2014-07-11 73 views

回答

10

不,它們都編譯到完全相同的IL。

更容易看到實際上是否給予lambda body一些依賴於狀態的東西 - 否則編譯器會爲每個lambda緩存一個委託實例。但是,例如:

using System; 

class Test 
{ 
    bool value = DateTime.Now.Hour == 10; 

    void Cast() 
    { 
     if (((Func<bool>)(() => value))()) 
     { 
      Console.WriteLine("Yes"); 
     } 
    } 

    void New() 
    { 
     if (new Func<bool>(() => value)()) 
     { 
      Console.WriteLine("Yes"); 
     } 
    } 

    static void Main() 
    { 
     new Test().Cast(); 
     new Test().New(); 
    } 
} 

現在IL爲Cast是:

.method private hidebysig instance void Cast() cil managed 
{ 
    // Code size  39 (0x27) 
    .maxstack 2 
    .locals init (bool V_0) 
    IL_0000: nop 
    IL_0001: ldarg.0 
    IL_0002: ldftn  instance bool Test::'<Cast>b__0'() 
    IL_0008: newobj  instance void class [mscorlib]System.Func`1<bool>::.ctor(object, 
                       native int) 
    IL_000d: callvirt instance !0 class [mscorlib]System.Func`1<bool>::Invoke() 
    IL_0012: ldc.i4.0 
    IL_0013: ceq 
    IL_0015: stloc.0 
    IL_0016: ldloc.0 
    IL_0017: brtrue.s IL_0026 
    IL_0019: nop 
    IL_001a: ldstr  "Yes" 
    IL_001f: call  void [mscorlib]System.Console::WriteLine(string) 
    IL_0024: nop 
    IL_0025: nop 
    IL_0026: ret 
} // end of method Test::Cast 

和IL爲New是:

.method private hidebysig instance void New() cil managed 
{ 
    // Code size  39 (0x27) 
    .maxstack 2 
    .locals init (bool V_0) 
    IL_0000: nop 
    IL_0001: ldarg.0 
    IL_0002: ldftn  instance bool Test::'<New>b__1'() 
    IL_0008: newobj  instance void class [mscorlib]System.Func`1<bool>::.ctor(object, 
                       native int) 
    IL_000d: callvirt instance !0 class [mscorlib]System.Func`1<bool>::Invoke() 
    IL_0012: ldc.i4.0 
    IL_0013: ceq 
    IL_0015: stloc.0 
    IL_0016: ldloc.0 
    IL_0017: brtrue.s IL_0026 
    IL_0019: nop 
    IL_001a: ldstr  "Yes" 
    IL_001f: call  void [mscorlib]System.Console::WriteLine(string) 
    IL_0024: nop 
    IL_0025: nop 
    IL_0026: ret 
} // end of method Test::New 

正如你可以看到,他們是相同的除了調用ldftn,它只是使用適當的編譯器生成的方法。

+1

我很好奇爲什麼編譯器不會在這裏使用相同的委託實例,因爲這兩個匿名函數具有相同的捕獲變量('值')。 –

+0

爲什麼'((()=> true)())'不起作用,它需要被鑄造?編譯器應該能夠推斷'Func '的類型? – ca9163d9

+0

@ dc7a9163d9:爲什麼?它可以是* any *委託類型,沒有任何參數,並且可以轉換爲'true'的返回類型。 –

相關問題