在匿名方法中使用 MethodInfo.GetCurrentMethod()

发布于 2024-10-12 16:07:55 字数 260 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北方。的韩爷 2024-10-19 16:07:55

你可以在外面捕捉它:

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

除此之外;不。

You could capture it outside:

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

Other than that; no.

千仐 2024-10-19 16:07:55

不,没有。这就是为什么它是一个匿名方法。该名称由编译器自动生成,并保证唯一。如果您想获取调用方法名称,您可以将其作为参数传递:

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

或者如果您确实想要一个有意义的名称,您将需要提供它:

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

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

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);
}
殤城〤 2024-10-19 16:07:55

如果您正在寻找获取匿名方法所在函数的名称,您可以遍历堆栈并获取调用方法的名称。但请注意,只有当您所需的方法名称在层次结构中向上一级时,这才有效。
也许有一种方法可以向上移动,直到到达非匿名方法。

欲了解更多信息,请参阅:
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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文