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

断了今生、忘了曾经 提交于 2019-11-29 02:09:36

You should use debugging API and debug your program from another process. Writing your own managed debugger is not trivial, but at least supported way of achieving your stated goal.

To my knowledge there is nothing in managed .Net framwork that you can use to collect information about run-time state of local variables of a method.

Note that there are enough cases when values for local variables do not exist to make writing general code to handle them complex:

  • method can be inlined (local variables will be merged with calling methods)
  • local variables can be optimized out
  • local variable can get out of scope and be garbage collected befor end of method.
   System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
        System.Diagnostics.StackFrame frame = trace.GetFrame(0);
        MethodBase method = frame.GetMethod();
        MethodBody methodBody = method.GetMethodBody();
        if (methodBody != null)
        {
            foreach (var local in methodBody.LocalVariables)
            {
                Console.WriteLine(local);
            }
        }
        Console.ReadKey();

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 is available on GitHub as part of the PADRE ( Pluggable Automatic Debugging and Reporting Engine)repository

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