C# reusable function to dump current value of local variables

一个人想着一个人 提交于 2019-11-28 22:05:41
Jeff

See this related question:

Is there a simple way to obtain all the local variables in the current stack frame in C# (or CIL)

The short answer is: you can't get the values of the local variables because they're allocated directly on the stack at runtime, and thus are not available via reflection. The only way to do this is via the debugger API...and it's far from trivial. Further, this would only work if your custom debugger is actually attached to the process.

A better, more feasible option might be via assembly weaving. You said you don't want to have the method have to know the specific names of local variables to access when logging their values. I would suggest creating two methods:

static void LogVariables();

and

static void LogVariables(params string[] names, params object[] values);

Add a post build task that calls an assembly weaving routine that swaps out the first LogVariables call with the second, but explicitly providing the variable names/values to the method. You can write this routine to modify the assembly using Mono Cecil (there are other tools too that can do this).

http://www.mono-project.com/Cecil

It is possible by using external debugger for managed code. See "managed debugger sample" for how it is done: http://blogs.msdn.com/b/jmstall/archive/2004/09/30/236281.aspx (includes link to the sample and more information)

Consider to write minidumps using a custom PostSharp aspect (with IL transformation).

A shared debuging engine library, written in C#. is available on NuGet as Microsoft.Samples.Debugging.MdbgEngine.

The code of PostSharp aspect is available on GitHub as part of the PADRE ( Pluggable Automatic Debugging and Reporting Engine)repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!