https://docs.microsoft.com/zh-cn/dotnet/api/system.diagnostics.stackframe?view=netframework-3.0
https://docs.microsoft.com/zh-cn/dotnet/api/system.diagnostics.stacktrace?view=netframework-3.0
测试代码如下:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConsoleApplication2
{class Program{static void Main(string[] args){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());Console.WriteLine("------------------------------------------------");SayHello();}static void SayHello(){StackFrame stackFrame = new StackTrace(new StackFrame(true)).GetFrame(0);Console.WriteLine("Hello~");Console.WriteLine(" Stack trace for current level: {0}", stackFrame.ToString());Console.WriteLine("File Name: {0}", stackFrame.GetFileName());Console.WriteLine("Method Name: {0}", stackFrame.GetMethod().Name);Console.WriteLine("Line Number: {0}", stackFrame.GetFileLineNumber());Console.WriteLine("Column Number: {0}", stackFrame.GetFileColumnNumber());}}
}
程序运行结果:
Main方法中的StackTrace对象定义位置(行和列)如下:
SayHello方法中的StackTrace对象定义位置(行和列)如下: