回答"哪种方法叫我?" 在.NET的运行时?或者代码可以读取CallStack数据吗?

pen*_*ake 2 reflection methods callstack runtime call

假设有methodA(),methodB()和methodC().

并且在运行时调用methodC().

有可能知道从哪个方法调用methodC()?

我在想是否可以在运行时读取CallStack以进行某些检查?如果是,我认为这应该不是什么大问题.

有任何想法吗?

谢谢!

Wim*_*dse 7

使用StackTrace和StackFrame类.例如:

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

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