在方法中发生异常时,跟踪/记录所有局部变量值的任何通用方法?(在C#3中)
答案:使用PostSharp(策略注入),XTraceMethodBoundary属性,覆盖OnException.这会记录所有方法输入和返回参数类型和值.我修改了PostSharp以添加一个简单的方法来记录参数.不完美但足够好
private static void TraceMethodArguments(MethodExecutionEventArgs eventArgs) { object[] parameters = eventArgs.GetReadOnlyArgumentArray(); if (parameters != null) { string paramValue = null; foreach (object p in parameters) { Type _type = p.GetType(); if (_type == typeof(string) || _type == typeof(int) || _type == typeof(double) || _type == typeof(decimal)) { paramValue = (string)p; } else if (_type == typeof(XmlDocument)) { paramValue = ((XmlDocument)p).OuterXml; } else { //try to serialize try { XmlSerializer _serializer = new XmlSerializer(p.GetType()); StringWriter _strWriter = new StringWriter(); _serializer.Serialize(_strWriter, p); paramValue = _strWriter.ToString(); } catch { paramValue = "Unable to Serialize Parameter"; } } Trace.TraceInformation("[" + Process.GetCurrentProcess().Id + "-" + Thread.CurrentThread.ManagedThreadId.ToString() + "]" + " Parameter: " + paramValue); } } }
基本上你不能.Reflection允许您获取实例(和静态)变量,但是如果要记录局部变量,则必须明确地执行此操作.您可以使用性能分析API做得更好,但这将是一个非常极端的步骤.