在匿名方法中使用 MethodInfo.GetCurrentMethod()
public static void Main(string[] args)
{
Action a = () => Console.WriteLine(MethodInfo.GetCurrentMethod().Name);
a();
}
此代码将返回一个模糊的字符串,如下所示:b__0
。
有没有办法忽略匿名方法并获得更易读的方法名称?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以在外面捕捉它:
除此之外;不。
You could capture it outside:
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:
or if you really want a meaningful name you will need to provide it:
如果您正在寻找获取匿名方法所在函数的名称,您可以遍历堆栈并获取调用方法的名称。但请注意,只有当您所需的方法名称在层次结构中向上一级时,这才有效。
也许有一种方法可以向上移动,直到到达非匿名方法。
欲了解更多信息,请参阅:
http://www.csharp-examples.net/reflection-calling-method-名称/
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/