对于一个lambda为什么会反射回这样一个奇怪的名字? [英] Why does reflection return such a weird name for a lambda?

查看:139
本文介绍了对于一个lambda为什么会反射回这样一个奇怪的名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code:

class Program
{
    static void Main(string[] args)
    {
        Action whatToDo = () => {
            var member = (MemberInfo)(MethodBase.GetCurrentMethod());
            Thread.Sleep(0); //whatever, need something to put a breakpoint on
        };
        whatToDo();
    }
}

当我运行它,并用手表看势必成员引用我看到 MemberInfo.Name 属性的值为<主>。b__0

when I run it and use watch to look inside the object bound to member reference I see that MemberInfo.Name property has value <Main>b__0.

这看起来很奇怪。为什么不反思利用 whatToDo 的名字吗?如果我有更多的一款动作具有相同签名的一个成员函数中 - ?我怎么会知道哪一个是报道

This looks weird. Why wouldn't reflection make use of whatToDo name? What if I had more that one action with the same signature inside one member function - how would I tell which one is reported?

为什么这样一个奇怪的名字被反射回来了?

Why is such a weird name returned by reflection?

推荐答案

这是转换为代表的lambda EX pressions转化为方法。您的code是等价于:

Lambda expressions which are being converted to delegates are transformed into methods. Your code is equivalent to:

class Program
{
    static void Main(string[] args)
    {
        Action whatToDo = MyLambda; // Method group conversion
        whatToDo();
    }

    static void MyLambda()
    {
        var member = (MemberInfo)(MethodBase.GetCurrentMethod());
        Thread.Sleep(0); //whatever, need something to put a breakpoint on
    }
}

...不同的是编译器足够聪明来创建新类在必要时对捕获的变量等。而在我的转型额外的方法被称为 MyLambda ,在C#编译器生成的难言的名字的哪些是无效的C#标识符(避免直接访问他们等的碰撞,prevent你)。

... except that the compiler is smart enough to create new classes where necessary for captured variables etc. While in my transformation the extra method is called MyLambda, the C# compiler generates unspeakable names which aren't valid C# identifiers (to avoid collisions, prevent you from accessing them directly etc).

这篇关于对于一个lambda为什么会反射回这样一个奇怪的名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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