2010-06-10 34 views

回答

2

我編譯的代碼,然後用ILDASM反編譯,這是發生了什麼:

SquareDelegate ss = x => { return x * x; }; 

編譯成

IL_0009: ldftn  int32 MiscTestApp.Program::'<Main>b__0'(int32) 
IL_000f: newobj  instance void MiscTestApp.SquareDelegate::.ctor(object, 
                    native int) 

.method private hidebysig static int32 
     '<Main>b__0'(int32 x) cil managed 
{ 
    // square and return x 
} 

.class public auto ansi sealed MiscTestApp.SquareDelegate 
    extends [mscorlib]System.MulticastDelegate 
{ 
    // delegate implementation 
} 

基本上,淨編譯SquareDelegate到延伸System.MulticastDelegate一個類,然後每當創建委託時,它創建使用臨時方法b__0的SquareDelegate類(IL_0009 ...)的一個實例。編譯器生成私有靜態方法b__0來表示lambda表達式。 通過這種方式,每個lambda將在編譯期間轉換爲相應的私有方法。由於(據我所知)你不能使用原始的lambda表達式(它總是轉換爲Action,Func或其他委託類型),所有lambda表達式都是內部委託。

相關問題