How can I find the method that called the current method?

后端 未结 19 1973
猫巷女王i
猫巷女王i 2020-11-21 22:50

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but

19条回答
  •  深忆病人
    2020-11-21 23:08

    In general, you can use the System.Diagnostics.StackTrace class to get a System.Diagnostics.StackFrame, and then use the GetMethod() method to get a System.Reflection.MethodBase object. However, there are some caveats to this approach:

    1. It represents the runtime stack -- optimizations could inline a method, and you will not see that method in the stack trace.
    2. It will not show any native frames, so if there's even a chance your method is being called by a native method, this will not work, and there is in-fact no currently available way to do it.

    (NOTE: I am just expanding on the answer provided by Firas Assad.)

提交回复
热议问题