用C#获取当前函数名,当前代码行,源代码文件

用C#获取当前函数名,当前代码行,源代码文件

//一.获取当前函数名:
 
class Program
{   
    static void Main(string[] args)
    {       
        Console.WriteLine(test());  
    }  

    static string Test()  
    {      
        var st = new System.Diagnostics.StackTrace();
        return st.GetFrame(0).ToString();  
    }
}

结果:Test at offset 72 in file:line:column :0:0,Test就是当前函数。
 
//二.获取源码文件名,当前函数,当前代码行,列:
 
StackTrace st = new StackTrace(new StackFrame(true));
Console.WriteLine(" Stack trace for current level: {0}", st.ToString());
StackFrame sf = st.GetFrame(0);
Console.WriteLine(" File: {0}", sf.GetFileName());
Console.WriteLine(" Method: {0}", sf.GetMethod().Name);
Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber());Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());

你可能感兴趣的:(C#,c#)