“DisplayClass"是什么?调用 lambda 时名称是什么意思? [英] What does "DisplayClass" name mean when calling lambda?

查看:29
本文介绍了“DisplayClass"是什么?调用 lambda 时名称是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个答案,当代码使用来自 lambda 方法内部的局部变量时,编译器将生成额外的可以具有名称的类例如 c__DisplayClass1.例如以下(完全没用的)代码:

According to this answer when code uses local variables from inside lambda methods the compiler will generate extra classes that can have name such as c__DisplayClass1. For example the following (completely useless) code:

class Program
{
    static void Main()
    {
        try {
            implMain();
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }

    static void implMain()
    {
        for (int i = 0; i < 10; i++) {
            invoke(() => {
                Console.WriteLine(i);
                throw new InvalidOperationException();
            });
        }
    }
    static void invoke(Action what)
    {
        what();
    }
}

输出如下调用栈:

System.InvalidOperationException
at ConsoleApplication1.Program.<>c__DisplayClass2.<implMain>b__0()
at ConsoleApplication1.Program.invoke(Action what)
at ConsoleApplication1.Program.implMain()
at ConsoleApplication1.Program.Main()

请注意,其中有 c__DisplayClass2,它是编译器生成的用于保存循环变量的类的名称.

Note that there's c__DisplayClass2 in there which is a name of a class generated by the compiler to hold the loop variable.

根据这个答案 c__DisplayClass意思是"

c --> 匿名方法闭包类(DisplayClass")

c --> anonymous method closure class ("DisplayClass")

好的,但这里的DisplayClass"是什么意思?

Okay, but what does "DisplayClass" mean here?

这个生成的类显示"了什么?换句话说,为什么它不是MagicClass"或GeneratedClass"或任何其他名称?

What does this generated class "display"? In other words why is it not "MagicClass" or "GeneratedClass" or any other name?

推荐答案

来自 Eric Lippert 对相关问题的回答:

闭包类被称为DisplayClass"的原因有点不幸:这是调试器团队用来描述在调试器中显示时具有特殊行为的类的行话.显然,我们不希望在调试代码时将x"显示为一个不可能命名的类的字段;相反,您希望它看起来像任何其他局部变量.调试器中有特殊的装置来处理这种显示类的操作.它可能应该被称为ClosureClass",以便更容易阅读反汇编.

The reason that a closure class is called "DisplayClass" is a bit unfortunate: this is jargon used by the debugger team to describe a class that has special behaviours when displayed in the debugger. Obviously we do not want to display "x" as a field of an impossibly-named class when you are debugging your code; rather, you want it to look like any other local variable. There is special gear in the debugger to handle doing so for this kind of display class. It probably should have been called "ClosureClass" instead, to make it easier to read disassembly.

这篇关于“DisplayClass"是什么?调用 lambda 时名称是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆