Using MethodInfo.GetCurrentMethod() in anonymous methods

笑着哭i 提交于 2019-12-01 16:49:17

You could capture it outside:

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

Other than that; no.

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);
}

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/

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