How to get the name of the class which contains the method which called the current method?

前端 未结 4 1488
刺人心
刺人心 2021-01-01 12:37

I have a requirement where I need to know the name of the class (ApiController) which has a method (GetMethod) which is called by another m

4条回答
  •  灰色年华
    2021-01-01 13:15

    using System.Diagnostics;
    
    var className = new StackFrame(1).GetMethod().DeclaringType.Name;
    

    Goes to the previous level of the Stack, finds the method, and gets the type from the method. This avoids you needing to create a full StackTrace, which is expensive.

    You could use FullName if you want the fully qualified class name.

    Edit: fringe cases (to highlight the issues raised in comments below)

    1. If compilation optimizations are enabled, the calling method may be inlined, so you may not get the value you expect. (Credit: Johnbot)
    2. async methods get compiled into a state machine, so again, you may not get what you expect. (Credit: Phil K)

提交回复
热议问题