Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 显示编译器生成的闭包代码_C#_Closures - Fatal编程技术网

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));
}