I have this 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();
}
}
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
.
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 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
}
}
... 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.