我写了这个非常基本的程序来检查编译器在幕后做了什么:
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++;
}
}
那很好,我知道他需要这样做来处理我的关闭。但是,我看不到他是如何使用这个类的。我的意思是我应该能找到在某处实例化“&lt;&gt; c__DisplayClass1”的代码,我错了吗?
编辑
如果我点击增加方法,它看起来像是:
private static Func<int> Increase()
{
int counter = 0;
return delegate {
return counter++;
};
}
答案 0 :(得分: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);
}
除非您关闭其优化,否则Reflector不会显示该代码,但它应该在那里。要么关闭Reflector的优化,要么使用ildasm。