从方法中检索调用方法名称 [英] Retrieving the calling method name from within a method

查看:26
本文介绍了从方法中检索调用方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对象中有一个方法,该方法从对象内的多个位置调用.是否有一种快速简便的方法来获取调用此流行方法的方法的名称.

I have a method in an object that is called from a number of places within the object. Is there a quick and easy way to get the name of the method that called this popular method.

伪代码示例:

public Main()
{
     PopularMethod();
}

public ButtonClick(object sender, EventArgs e)
{
     PopularMethod();
}

public Button2Click(object sender, EventArgs e)
{
     PopularMethod();
}

public void PopularMethod()
{
     //Get calling method name
}

PopularMethod() 内,如果 Main 是从 Main 调用的,我想看看它的值......我想要查看ButtonClick";如果 PopularMethod() 是从 ButtonClick

Within PopularMethod() I would like to see the value of Main if it was called from Main ... I'd like to see "ButtonClick" if PopularMethod() was called from ButtonClick

我正在查看 System.Reflection.MethodBase.GetCurrentMethod() 但这不会让我找到调用方法.我查看了 StackTrace 类,但我真的不喜欢在每次调用该方法时运行整个堆栈跟踪.

I was looking at the System.Reflection.MethodBase.GetCurrentMethod() but that won't get me the calling method. I've looked at the StackTrace class but I really didn't relish running an entire stack trace every time that method is called.

推荐答案

我认为不跟踪堆栈是无法完成的.但是,这样做相当简单:

I don't think it can be done without tracing the stack. However, it's fairly simple to do that:

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name); // e.g.

但是,我认为您真的必须停下来问问自己是否有必要这样做.

However, I think you really have to stop and ask yourself if this is necessary.

这篇关于从方法中检索调用方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆