Answering “Which method called me?” at the run-time in .NET? Or is CallStack data readable by the code?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 02:14:43

问题


Presume that there are methodA() , methodB() and methodC().

And methodC() is called at the run-time.

Is is possible to know methodC() is called from what method?

I was thinking if CallStack can be read at the run-time for some checks? If yes, I think it should not be a big deal.

Any ideas?

Thanks!


回答1:


Use the StackTrace and StackFrame classes. For example:

StackTrace stackTrace = new StackTrace();          
StackFrame[] stackFrames = stackTrace.GetFrames();

foreach (StackFrame stackFrame in stackFrames)
{
    string method = stackFrame.GetMethod().Name;
    // do some stuff with method
}



回答2:


Yes, the call stack can be read at runtime using StackTrace.Get­Frames.



来源:https://stackoverflow.com/questions/1873998/answering-which-method-called-me-at-the-run-time-in-net-or-is-callstack-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!