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

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

    Why not simply pass the name as constructor parameter? This doesn't hide the dependency, unlike StackFrame/StackTrace.

    For example:

    public class ApiController
    {
        private readonly OtherClass _otherClass = new OtherClass(nameof(ApiController));
    
        public void GetMethod()
        {
            _otherClass.OtherMethod();
        }
    }
    
    public class OtherClass
    {
        private readonly string _controllerName;
    
        public OtherClass(string controllerName)
        {
            _controllerName = controllerName;
        }
    
        public void OtherMethod()
        {
            Console.WriteLine(_controllerName);
        }
    }
    

提交回复
热议问题