Is there compile-time access to line numbers in C#?

后端 未结 4 2191
日久生厌
日久生厌 2021-02-12 22:39

I\'m writing a C# program using Visual Studio 2010 where I want to write out certain events to a log file and include the line number the code was on when that happened.

4条回答
  •  迷失自我
    2021-02-12 23:24

    One option would be to use the StackTrace class, like so

     [Conditional("DEBUG")]
        public static void DebugPrintTrace()
        {
            StackTrace st = new StackTrace(true);
            StackFrame sf = st.GetFrame(1);
            Console.WriteLine("Trace "
                + sf.GetFileName() + " "
                + sf.GetMethod().Name + ":"
                + sf.GetFileLineNumber() + "\n");
        } 
    

提交回复
热议问题