开发者

Using MethodInfo.GetCurrentMethod() in anonymous methods

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?


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜