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

问题描述

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.

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

09-05 09:38
查看更多