C#使用StackTrace获取方法被谁调用

在方法中扔进这段

System.Diagnostics.Debug.WriteLine(new string('*', 78));
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
System.Diagnostics.StackFrame[] sfs = st.GetFrames();
for (int u = 0; u < sfs.Length; ++u)
{
   System.Reflection.MethodBase mb = sfs[u].GetMethod();
    System.Diagnostics.Debug.WriteLine("[CALL STACK][{0}]: {1}.{2}", u, mb.DeclaringType.FullName, mb.Name);
}

然后就能在output窗口(Alt+2)看到类似

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
******************************************************************************
[CALL STACK][0]: WindowsFormsApplication1.Form1.button1_Click
[CALL STACK][1]: System.Windows.Forms.Button.OnMouseUp
[CALL STACK][2]: System.Windows.Forms.Control.WmMouseUp
[CALL STACK][3]: System.Windows.Forms.Control.WndProc
[CALL STACK][4]: System.Windows.Forms.ButtonBase.WndProc
[CALL STACK][5]: System.Windows.Forms.Button.WndProc
[CALL STACK][6]: System.Windows.Forms.NativeWindow.DebuggableCallback
[CALL STACK][7]: System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW
[CALL STACK][8]: System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW
[CALL STACK][9]: System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
[CALL STACK][10]: System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner
[CALL STACK][11]: System.Windows.Forms.Application+ThreadContext.RunMessageLoop
[CALL STACK][12]: WindowsFormsApplication1.Program.Main
[CALL STACK][13]: System.AppDomain._nExecuteAssembly
[CALL STACK][14]: Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly
[CALL STACK][15]: System.Threading.ExecutionContext.RunInternal
[CALL STACK][16]: System.Threading.ExecutionContext.Run
[CALL STACK][17]: System.Threading.ExecutionContext.Run
[CALL STACK][18]: System.Threading.ThreadHelper.ThreadStart

再高(dan)级(teng)一点 ,写个公用的静态方法,并用上“DEBUG”条件之,然后……在需要的地方调用之

[System.Diagnostics.Conditional("DEBUG")]
static public void OutputCallStack()
{
    System.Diagnostics.Debug.WriteLine(new string('*', 78));
    System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
    System.Diagnostics.StackFrame[] sfs = st.GetFrames();
    for (int u = 1; u < sfs.Length; ++u)
    {
System.Reflection.MethodBase mb = sfs[u].GetMethod();
System.Diagnostics.Debug.WriteLine("[CALL STACK][{0}]: {1}.{2}", u, mb.DeclaringType.FullName, mb.Name);
    }
}

思考题:能否利用扩展方法扩展到Debug命名空间下呢?

另:西加加得到调用堆栈的东东都在execinfo.h 点击乘坐直达列车

http://blog.csdn.net/yuxuac/article/details/12574713

http://www.cnblogs.com/isabelincoln/archive/2006/11/02/547544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值