C#
using System; using System.Diagnostics; namespace StackPrint { class Program { static void Main(string[] args) { SingleFunc(); Console.ReadKey(); } private static void SingleFunc() { SmallFunc(); } static void SmallFunc() { //取得Stack物件 // true means get line numbers. StackTrace st = new StackTrace(true); //宣告stack 成員 StackFrame f ; //0 :目前method, 1:取得前一個呼叫method f=st.GetFrames()[1]; Console.Write(f); //PrintAllStack(); } //顯示stack所有內容 static void PrintStack() { // true means get line numbers. StackTrace st = new StackTrace(true); foreach (StackFrame f in st.GetFrames()) { Console.Write(f); } } }
VB
Imports System Imports System.Diagnostics Module Module1 Sub Main() SingleFunc() Console.ReadKey() End Sub Sub SingleFunc() SmallFunc() End Sub Sub SmallFunc() '取得Stack物件 ' true means get line numbers. Dim st As StackTrace = New StackTrace(True) '宣告stack 成員 Dim f As StackFrame '0 :目前method, 1:取得前一個呼叫method f = st.GetFrames()(1) Console.Write(f) 'PrintAllStack() End Sub '顯示stack所有內容 Sub PrintStack() ' true means get line numbers. Dim st As StackTrace = New StackTrace(True) Dim f As StackFrame For Each f In st.GetFrames() Console.Write(f) Next End Sub End Module
上一呼叫method
StackTrace所有內容
另外也可以利用呼叫端資訊
呼叫端資訊 (C# 和 Visual Basic)
using System.Runtime.CompilerServices using System.Diagnostics; public void DoProcessing() { TraceMessage("Something happened."); } public void TraceMessage(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Trace.WriteLine("message: " + message); Trace.WriteLine("member name: " + memberName); Trace.WriteLine("source file path: " + sourceFilePath); Trace.WriteLine("source line number: " + sourceLineNumber); }
沒有留言:
張貼留言