December 2007
Intermediate to advanced
896 pages
19h 57m
English
You are building a tool that examines code, and you need to get access to the local variables within a method.
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 TestGet LocalVars()
{
Process current = Process.GetCurrentProcess();
// Get the path of the current module.
string path = current.MainModule.FileName;
// Get all local var info for the CSharpRecipes.Reflection.GetLocalVars method. System.Collections.ObjectModel.ReadOnlyCollection<LocalVariableInfo> vars = (System.Collections.ObjectModel.ReadOnlyCollection<LocalVariableInfo>) ...Read now
Unlock full access