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

后端 未结 19 1719
猫巷女王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:14

    Try this:

    using System.Diagnostics;
    // Get call stack
    StackTrace stackTrace = new StackTrace(); 
    // Get calling method name
    Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
    

    one-liner:

    (new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name
    

    It is from Get Calling Method using Reflection [C#].

提交回复
热议问题