Using MethodInfo.GetCurrentMethod() in anonymous methods

半腔热情 提交于 2019-12-01 15:48:16

问题


public static void Main(string[] args)
{
    Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
    a();
}

This code will return an obscure string like so: <Main>b__0.

Is there a way of ignoring the anonymous methods and get a more readable method name?


回答1:


You could capture it outside:

var name = MethodInfo.GetCurrentMethod().Name + ":subname";
Action a = () => Console.WriteLine(name);

Other than that; no.




回答2:


No, there isn't. That's why it is an anonymous method. The name is automatically generated by the compiler and guaranteed to be unique. If you want to get the calling method name you could pass it as argument:

public static void Main()
{
    Action<string> a = name => Console.WriteLine(name);
    a(MethodInfo.GetCurrentMethod().Name);
}

or if you really want a meaningful name you will need to provide it:

public static void Main()
{
    Action a = MeaningfullyNamedMethod;
    a();
}

static void MeaningfullyNamedMethod()
{
    Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
}



回答3:


If you are looking for getting the name of the function in which the anonymous method resides in you could travel the stack and get the name of the calling method. Do note though, that this would only work as long as your desired method name is one step up in the hierarchy. Maybe there's a way of travelling up until you reach a non-anonymous method.

For more information see: http://www.csharp-examples.net/reflection-calling-method-name/



来源:https://stackoverflow.com/questions/4704910/using-methodinfo-getcurrentmethod-in-anonymous-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!