C# 显示编译器生成的闭包代码
我创建了一个小测试类:C# 显示编译器生成的闭包代码,c#,closures,C#,Closures,我创建了一个小测试类: public delegate int Adder(); class Example { static Adder CreateAdder() { int x = 0; return delegate { x++; return x; }; } public static void Test() { Adder add = Creat
public delegate int Adder();
class Example {
static Adder CreateAdder() {
int x = 0;
return delegate {
x++;
return x;
};
}
public static void Test() {
Adder add = CreateAdder();
Console.WriteLine(add());
Console.WriteLine(add());
Console.WriteLine(add());
}
}
x是一个闭包变量。现在,我可以使用Reflector查看编译器是否生成以下帮助器类:
[CompilerGenerated]
private sealed class <>c__DisplayClass0_0 {
public int x;
internal int <CreateAdder>b__0() {
int x = this.x;
this.x = x + 1;
return this.x;
}
}
[编译生成]
专用密封类c\uuu显示器Class0\u0{
公共int x;
内部整数b_u 0(){
int x=这个.x;
这个.x=x+1;
归还这个.x;
}
}
但是我看不出这个Helper类将如何在测试方法中使用。是否有可能使用Helper类来显示测试方法?事实上,令人兴奋的部分不在
Test()
中。因为Test()
只是调用一个委托(add
)
编译器生成的类用于CreateAdder()
:
专用静态加法器CreateAdder()
{
Example.c_uudisplayClass0_0 cDisplayClass00=新示例.c_uudisplayClass0_0();
cDisplayClass00.x=0;
返回新的加法器((对象)cDisplayClass00,_方法ptr(b_u0));
}
因此,要创建委托,需要实例化编译器生成的类的对象。代理以这个对象为目标,它是b_uu0
方法(表示您在匿名方法中所做的操作)
我过去常常反编译它。是Microsoft的替代方案。您可以使用ILDASM或JetBrain的dotPeek对程序集进行反编译,并查看
Test()
中的情况。谢谢。还有一个问题:您在dotPeek中看到编译器生成的类了吗?我没有:-(
// decompiled code is the same as original source
public static void Test()
{
Adder add = Example.CreateAdder();
Console.WriteLine(add());
Console.WriteLine(add());
Console.WriteLine(add());
}
private static Adder CreateAdder()
{
Example.<>c__DisplayClass0_0 cDisplayClass00 = new Example.<>c__DisplayClass0_0();
cDisplayClass00.x = 0;
return new Adder((object) cDisplayClass00, __methodptr(<CreateAdder>b__0));
}