无法看到编译器如何使用他为闭包创建的类

Chr*_*oph 5 c# compiler-construction reflector

我编写了这个非常基本的程序来检查编译器在幕后做了什么:

class Program
{
    static void Main(string[] args)
    {
        var increase = Increase();
        Console.WriteLine(increase());
        Console.WriteLine(increase());
        Console.ReadLine();
    }

    static Func<int> Increase()
    {
        int counter = 0;
        return () => counter++;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,当我用Reflector查看代码时,我确实看到编译器为我的闭包生成了一个类:

[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
    // Fields
    public int counter;

    // Methods
    public int <Increase>b__0()
    {
        return this.counter++;
    }
}
Run Code Online (Sandbox Code Playgroud)

那很好,我知道他需要这样做来处理我的关闭.但是,我看不到他是如何使用这个类的.我的意思是我应该能找到在某处实例化"<> c__DisplayClass1"的代码,我错了吗?

编辑

如果我点击增加方法,它看起来像这样:

private static Func<int> Increase()
{
    int counter = 0;
    return delegate {
        return counter++;
    };
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 4

您应该在方法中找到它Increase,我希望该方法有一个如下的实现:

// Not actually valid C# code because of the names...
static Func<int> Increase()
{
    <>c__DisplayClass1 closure = new c__DisplayClass1();
    closure.counter = 0;
    return new Func<int>(closure.<Increase>b__0);
}
Run Code Online (Sandbox Code Playgroud)

除非您关闭其优化,否则 Reflector 不会向您显示该代码,但它应该在那里。要么关闭Reflector的优化,要么使用ildasm。