【发布时间】:2011-11-08 14:53:43
【问题描述】:
我编写了这个非常基本的程序来检查编译器在幕后所做的事情:
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++;
}
}
现在,当我使用 Reflector 查看代码时,我确实看到编译器为我的闭包生成了一个类,如下所示:
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
// Fields
public int counter;
// Methods
public int <Increase>b__0()
{
return this.counter++;
}
}
没关系,我知道他需要这样做来处理我的关闭。但是,我看不到他实际上是如何使用这个类的。我的意思是我应该能够在某处找到实例化“c__DisplayClass1”的代码,我错了吗?
编辑
如果我点击增加方法,它看起来像这样:
private static Func<int> Increase()
{
int counter = 0;
return delegate {
return counter++;
};
}
【问题讨论】:
-
你能把剩下的编译代码贴出来吗?尤其是你的 Main 方法。
-
@dowhilefor:Main 方法实际上会很无聊。它只是调用一个方法来获取委托,调用委托几次并打印出结果,然后调用
Console.ReadLine。
标签: c# compiler-construction reflector