
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
786
|
Chapter 13: Reflection
13.15 Accessing Local Variable Information
Problem
You are building a tool that examines code and you need to get access to the local
variables within a method.
Solution
Use the LocalVariables property on the MethodBody class to return an IList of
LocalVariableInfo objects, each of which describes a local variable within the
method:
public static IList<LocalVariableInfo> GetLocalVars(string asmPath,
string typeName, string methodName)
{
Assembly asm = Assembly.LoadFrom(asmPath);
Type asmType = asm.GetType(typeName);
MethodInfo mi = asmType.GetMethod(methodName);
MethodBody mb = mi.GetMethodBody( );
IList<LocalVariableInfo> vars = mb.LocalVariables;
// Display information about each local variable.
foreach (LocalVariableInfo lvi in vars)
{
Console.WriteLine("IsPinned: " + lvi.IsPinned);
Console.WriteLine("LocalIndex: " + lvi.LocalIndex);
Console.WriteLine("LocalType.Module: " + lvi.LocalType.Module);
Console.WriteLine("LocalType.FullName: " + lvi.LocalType.FullName);
Console.WriteLine("ToString( ): " + lvi.ToString( ));
}
return (vars);
}
The GetLocalVars method can be called using the following code:
public static void TestGetLocalVars( )
{
Process current = Process.GetCurrentProcess( );
// Get the path of the current module.
string path = current.MainModule.FileName; ...