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

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

    You can achieve this by below code

    First you need to add namespace using System.Diagnostics;

    public class OtherClass
    {
        public void OtherMethod()
        {
            StackTrace stackTrace = new StackTrace();
    
            string callerClassName = stackTrace.GetFrame(1).GetMethod().DeclaringType.Name;
            string callerClassNameWithNamespace = stackTrace.GetFrame(1).GetMethod().DeclaringType.FullName;
    
            Console.WriteLine("This is the only name of your class:" + callerClassName);
            Console.WriteLine("This is the only name of your class with its namespace:" + callerClassNameWithNamespace);
        }
    }
    

    The instance of stackTrace is depend upon your implementation environment. you may defined it locally or globally

    OR

    You may use below method without creating StackTrace instance

    public class OtherClass
    {
        public void OtherMethod()
        {
            string callerClassName = new StackFrame(1).GetMethod().DeclaringType.Name;
            string callerClassNameWithNamespace = new StackFrame(1).GetMethod().DeclaringType.FullName;
    
            Console.WriteLine("This is the only name of your class:" + callerClassName);
            Console.WriteLine("This is the only name of your class with its namespace:" + callerClassNameWithNamespace);
        }
    }
    

    Try this may it help you

提交回复
热议问题