2010-06-10 75 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表达式都是内部委托。

相关问题