tags:

views:

113

answers:

1

I want to get a detailed log about my stack trace. I can get a StackFrame and then the method and then get all the parameters of that method. Just as the following code:

            StackTrace st = new StackTrace();
            StackFrame[] sfs = st.GetFrames();
            foreach (StackFrame sf in sfs)
            {
                MethodBase method = sf.GetMethod();
                ParameterInfo[] pis = method.GetParameters();
                foreach (ParameterInfo pi in pis)
                {
                      ....
                }
                Console.WriteLine(method.Name);
            }

But how could I get the local variables infomation within a method?

Could someone shed some light on me?

Many thanks.

+3  A: 

You might want to look into LocalVariableInfo.

Example fom MSDN // Get method body information.

MethodInfo mi = typeof(Example).GetMethod("MethodBodyExample");
MethodBody mb = mi.GetMethodBody();
Console.WriteLine("\r\nMethod: {0}", mi);

// Display the general information included in the 
// MethodBody object.
Console.WriteLine("    Local variables are initialized: {0}", 
    mb.InitLocals);

foreach (LocalVariableInfo lvi in mb.LocalVariables)
{
    Console.WriteLine("Local variable: {0}", lvi);
}
Filip Ekberg
Thanks Filip. Just a further question, could I get the name/type/value of the local variables?
smwikipedia
@smwikipedia: no, you can't :) at least not in managed code. If you were to use the unmanaged profiling APIs, it could work, but it's not an easy piece of work.
Jb Evain
It wouldn't make any sense to get the value of the local variable since you are inspeciting it out of scope.
Filip Ekberg
Thanks, Filip. I just want to log and inspect the call stack info like a debugger does.
smwikipedia