无法看到编译器如何使用他为我的闭包创建的类
我编写了这个非常基本的程序来检查编译器在幕后做了什么:
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++;
};
}
I wrote this very basic programm to examine what the compiler is doing behind the scenes:
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++;
}
}
Now when I look at the code with Reflector I do see that the compiler generates a class for my closure like that:
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
// Fields
public int counter;
// Methods
public int <Increase>b__0()
{
return this.counter++;
}
}
That's fine and I'm aware that he needs to do that to handle my closure. However, what I can't see is how he is actually using this class. I mean I should be able to find code that instantiates "<>c__DisplayClass1" somewhere, am I wrong?
EDIT
If I click on the increase method it looks like that:
private static Func<int> Increase()
{
int counter = 0;
return delegate {
return counter++;
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在
Increase
方法中找到它,我希望该方法具有如下实现:除非您关闭其优化,否则 Reflector 不会向您显示该代码,但它应该在那里。要么关闭Reflector的优化,要么使用ildasm。
You should find it in the
Increase
method, which I'd expect to have an implementation along these lines:Reflector won't show you that code unless you turn off its optimization, but it should be there. Either turn off Reflector's optimization, or use ildasm.