C # reuse function to display the current value of local variables

I would like to write a reusable function that I can call in any method to record a snapshot of all local variables. For instance:

    void somemethod()
    {
        int a = 1;
        string s = "something";
        dumpLocalVariables("step 1", MethodInfo.GetCurrentMethod(), this);

        a++;
        string t = s + "else";
        dumpLocalVariables("step 2", MethodInfo.GetCurrentMethod(), this);
    }

I would like to get console output as follows:

step 1
    Int32 a = 1 
    String s = something
step 2
    Int32 a = 2
    String s = something
    String t = somethingelse

I want to avoid providing a specific list of local variable names.

The closest I could find was MethodInfo.GetCurrentMethod().GetMethodBody().LocalVariables, but I don't know how to access the values ​​of local variables using reflection.

void dumpLocalVariables(string context, MethodBase currentMethod, object obj)
{
    Console.WriteLine(context);
    MethodBody methodBody = currentMethod.GetMethodBody();
    foreach (LocalVariableInfo lvi in methodBody.LocalVariables)
    {
        string variableType = lvi.LocalType.Name;
        // how do I get this?
        string variableName = "variableNameHere";
        // how do I get this?    
        string variableValue = "variableValueHere";
        Console.WriteLine("   " + variableType  + " " + variableName + 
            " = " + variableValue);
    }
}

The reflection API is well suited for static analysis, but not for dynamic analysis like this. For example, a variable is tnot in scope during the first call dumpLocalVariables, but it still appears in the property LocalVariables MethodBody.

, API , . Developer Studio "locals", ? - ?

EDIT:

ILSpy , IL-, ldloc.0 ldloc.1, .

.locals init (
    [0] int32 a
    [1] string s
    [2] string t
)

IL_001b: ldloc.0  // this is a
IL_001c: ldc.i4.1
IL_001d: add
IL_001e: stloc.0
IL_001f: ldloc.1  // this is s
IL_0020: ldstr "else"
IL_0025: call string string::Concat(string, string)
IL_002a: stloc.2  // this is t

, - - , ? , , , - .

+5
3

:

# ( CIL)

: , , , . - API ... . , , .

, . , , . :

static void LogVariables();

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

-, , LogVariables , / . , Mono Cecil ( , ).

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

+7

minidumps PostSharp ( IL).

, #. NuGet Microsoft.Samples.Debugging.MdbgEngine.

PostSharp GitHub PADRE (Pluggable Automatic Debugging and Reporting Engine)

0

All Articles