StackTrace stackTrace = new StackTrace(); ParameterInfo[] parameters = stackTrace.GetFrame(1).GetMethod().GetParameters();
如上代码在调用微软的API时,只能获取参数的名称,不能获取参数的值。
在网上找了一个用PostSharp工具来获取函数参数名称和值,经整理代码如下:
class Program { static void Main(string[] args) { string filePath = @"C:\log.txt"; if (File.Exists(filePath)) { FileStream fs = File.Create(filePath); fs.Close(); } Trace.Listeners.Add(new LogTraceListener(filePath)); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); MyClass my = new MyClass(); my.MyMethod(44, "asdf qwer 1234", 3.14f, true); Console.ReadKey(); } } public class MyClass { public MyClass() { } #if DEBUG [Trace("DEBUG")] #endif public int MyMethod(int x, string someString, float anotherFloat, bool theBool) { return x + 1; } } [Serializable] public sealed class TraceAttribute : OnMethodBoundaryAspect { private readonly string category; public TraceAttribute(string category) { this.category = category; } public string Category { get { return category; } } public override void OnEntry(MethodExecutionArgs args) { Trace.WriteLine(string.Format("{2}----Entering {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name, DateTime.Now.ToString()), category); for (int x = 0; x < args.Arguments.Count; x++) { Trace.WriteLine(args.Method.GetParameters()[x].Name + " = " + args.Arguments.GetArgument(x)); } } public override void OnExit(MethodExecutionArgs args) { Trace.WriteLine("Return Value: " + args.ReturnValue); Trace.WriteLine(string.Format("{2}---Leaving {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name, DateTime.Now.ToString()), category); } } public sealed class LogTraceListener : TraceListener { public string FileName { set; get; } public LogTraceListener(string filename) { FileName = filename; } public override void Write(string message) { using (StreamWriter sw = new StreamWriter(FileName, true, Encoding.UTF8, Int16.MaxValue)) { sw.Write(message); } } public override void WriteLine(string message) { using (StreamWriter sw = new StreamWriter(FileName, true, Encoding.UTF8, Int16.MaxValue)) { sw.WriteLine(message); } } }
运行结果如图:
下载地址http://download.csdn.net/source/3540692