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

前端 未结 4 1468
刺人心
刺人心 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:12

    So it can be done like this,

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

    StackFrame represents a method on the call stack, the index 1 gives you the frame that contains the immediate caller of the currently executed method, which is ApiController.GetMethod() in this example.

    Now you have the frame, then you retrieve the MethodInfo of that frame by calling StackFrame.GetMethod(), and then you use the DeclaringType property of the MethodInfo to get the type in which the method is defined, which is ApiController.

提交回复
热议问题