问题描述
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.
这篇关于从方法内检索调用方法名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!