C#获取调用文件名,行号,方法

2022/8/8 14:23:15

本文主要是介绍C#获取调用文件名,行号,方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一.第一种方式
[DebuggerStepThrough] //跳过调式
        static void Print(string str,
                [CallerFilePath] string filePath = "",//文件路径
                [CallerLineNumber] int num = 0,       //行号
                [CallerMemberName] string name = "") //方法名
        {
            Console.WriteLine(str);
            Console.WriteLine("filePath {0}", filePath);
            Console.WriteLine("Line {0}", num);
            Console.WriteLine("Call from {0}", name);
        }

二.第二种方式:

1.获取行号

  /// <summary>
        /// Get line number of code dynamically
        /// </summary>
        /// <param name="skipFrames">number of frames to skip</param>
        /// <returns>line number of code after skipping frames</returns>
        public static int GetCodeLineNum(int skipFrames)
        {
            StackTrace st = new StackTrace(skipFrames, true);
            StackFrame fram = st.GetFrame(0);
            int lineNum = fram.GetFileLineNumber();
            return lineNum;
        }

2.获取文件路径

/// <summary>
        /// Get file name information of code dynamically
        /// </summary>
        /// <param name="skipFrames">number of frames to skip</param>
        /// <returns>file name information of code after skipping frames</returns>
        public static string GetCodeFileName(int skipFrames)
        {
            StackTrace st = new StackTrace(skipFrames, true);
            StackFrame fram = st.GetFrame(0);
            string source = fram.GetFileName();
            return source;
        }


这篇关于C#获取调用文件名,行号,方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程