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

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

问题描述


  

可能重复:结果
  <一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 of Main if it was called from Main ... I'd like to see "ButtonClick" if PopularMethod() was called from ButtonClick

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天全站免登陆