How do I find the type of the object instance of the caller of the current function?

前端 未结 5 685
误落风尘
误落风尘 2021-02-06 07:37

Currently I have the function CreateLog() for creating a a log4net Log with name after the constructing instance\'s class. Typically used as in:

class MessageRe         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 08:18

    Try the StackTrace.GetFrames method. It returns an array of all the StackFrame objects in the call stack. Your caller should be at index one.

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();
            Caller caller = new Caller();
            caller.FirstMethod(logger);
            caller.SecondMethod(logger);
        }
    }
    
    public class Caller
    {
        public void FirstMethod(Logger logger)
        {
            Console.Out.WriteLine("first");
            logger.Log();
        }
    
        public void SecondMethod(Logger logger)
        {
            Console.Out.WriteLine("second");
            logger.Log();
        }
    }
    
    public class Logger
    {
        public void Log()
        {
            StackTrace trace = new StackTrace();
            var frames = trace.GetFrames();
            Console.Out.WriteLine(frames[1].GetMethod().Name);
        }
    }
    

    this outputs

    first FirstMethod second SecondMethod

提交回复
热议问题