StackTrace用来表示一个堆栈跟踪,它是一个或多个堆栈帧的有序集合
[C#]//构造函数
public StackTrace(
int skipFrames, //堆栈中的帧数,将从其上开始跟踪。
bool fNeedFileInfo //如果为 true,则捕获文件名、行号和列号;否则为 false。
);
主要步骤:
1.StackTrace st = new StackTrace(1, true); //声明新实例
2.st.FrameCount; //得到栈的frame总数
3.StackFrame sf = st.GetFrame(i); //遍历所有frame
4.Console.WriteLine("Method: {0}", sf.GetMethod() ); //取得该frame的信息
输出结果:
Method: Void MyPublicMethod()
Method: Void Main(System.String[])
源代码:
using System;
namespace Duwamish7.SystemFramework
{
using System;
using System.Diagnostics;
class MyConsoleApp
{
[STAThread]
static void Main(string[] args)
{
MyConsoleApp myApp = new MyConsoleApp();
myApp.MyPublicMethod();
}
public void MyPublicMethod()
{
MyInnerClass helperClass = new MyInnerClass();
helperClass.ThrowsException();
}
class MyInnerClass
{
public void ThrowsException()
{
try
{
throw new Exception("A problem was encountered.");
}
catch (Exception)
{
// Create a StackTrace that captures
// filename, line number and column
// information, but hides the internal
// implementation from the user by skipping
// the first stack frame, which represents
// the ThrowsException method.
StackTrace st = new StackTrace(1, true);
for(int i =0; i< st.FrameCount; i++ )
{
StackFrame sf = st.GetFrame(i);
Console.WriteLine("Method: {0}", sf.GetMethod() );
}
Console.ReadLine();
}
}
}
}
}
[C#]//构造函数
public StackTrace(
int skipFrames, //堆栈中的帧数,将从其上开始跟踪。
bool fNeedFileInfo //如果为 true,则捕获文件名、行号和列号;否则为 false。
);
主要步骤:
1.StackTrace st = new StackTrace(1, true); //声明新实例
2.st.FrameCount; //得到栈的frame总数
3.StackFrame sf = st.GetFrame(i); //遍历所有frame
4.Console.WriteLine("Method: {0}", sf.GetMethod() ); //取得该frame的信息
输出结果:
Method: Void MyPublicMethod()
Method: Void Main(System.String[])
源代码:
using System;
namespace Duwamish7.SystemFramework
{
using System;
using System.Diagnostics;
class MyConsoleApp
{
[STAThread]
static void Main(string[] args)
{
MyConsoleApp myApp = new MyConsoleApp();
myApp.MyPublicMethod();
}
public void MyPublicMethod()
{
MyInnerClass helperClass = new MyInnerClass();
helperClass.ThrowsException();
}
class MyInnerClass
{
public void ThrowsException()
{
try
{
throw new Exception("A problem was encountered.");
}
catch (Exception)
{
// Create a StackTrace that captures
// filename, line number and column
// information, but hides the internal
// implementation from the user by skipping
// the first stack frame, which represents
// the ThrowsException method.
StackTrace st = new StackTrace(1, true);
for(int i =0; i< st.FrameCount; i++ )
{
StackFrame sf = st.GetFrame(i);
Console.WriteLine("Method: {0}", sf.GetMethod() );
}
Console.ReadLine();
}
}
}
}
}
浙公网安备 33010602011771号