从方法内检索调用方法名 [英] Retrieving the calling method name from within a method
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method\">How我能找到调用当前方法的方法?
块引用>我有在从一个数的对象内的地方称为对象的方法。是否有一个快速简便的方法来获得调用此方法流行的方法的名称。
伪code的例子:
公开的Main()
{
PopularMethod();
}公共ButtonClick(对象发件人,EventArgs的发送)
{
PopularMethod();
}公共Button2Click(对象发件人,EventArgs的发送)
{
PopularMethod();
}公共无效PopularMethod()
{
//获取调用方法名
}在
PopularMethod()
我想看看主要的价值
,如果它是从<$ C称为$ C>主 ...我想看到ButtonClick
如果PopularMethod()
从ButtonClick
我一直在寻找在
System.Reflection.MethodBase.GetCurrentMethod()
但这不会让我调用方法。我看了看堆栈跟踪
类,但我真的没津津乐道每一个方法被调用时运行的整个堆栈跟踪。解决方案我不认为它可以在不跟踪堆栈来完成。然而,这是相当简单的做到这一点:
堆栈跟踪堆栈跟踪=新的堆栈跟踪();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name); //例如不过,我觉得你真的要停下来问自己,如果这是必要的。
Possible Duplicate:
How can I find the method that called the current method?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.
Pseudo Code EXAMPLE:
public Main() { PopularMethod(); } public ButtonClick(object sender, EventArgs e) { PopularMethod(); } public Button2Click(object sender, EventArgs e) { PopularMethod(); } public void PopularMethod() { //Get calling method name }
Within
PopularMethod()
I would like to see the value ofMain
if it was called fromMain
... I'd like to see "ButtonClick
" ifPopularMethod()
was called fromButtonClick
I was looking at the
System.Reflection.MethodBase.GetCurrentMethod()
but that won't get me the calling method. I've looked at theStackTrace
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屋!