Is it possible with the classes in Reflection.Emit to modify a method
of an existing class?
I would like to print some diagnostic messages every time certain
methods are called. I don't want to start adding code to every part of
my program that calls these methods, and the code came as a DLL so I
can't modify the source.
Here's something close to what I've tried:
Assembly currentAssembly = Assembly.GetExecutingAssembly();
Type[] types = currentAssembly.GetTypes();
....//other unrelated code removed...
AppDomain appDomain = AppDomain.CurrentDomain;
AssemblyBuilder assbuild =
appDomain.DefineDynamicAssembly(currentAssembly.Ge tName(),
AssemblyBuilderAccess.Run);
//types[j] is the index in types of the type I need to modify.
ModuleBuilder myModuleBuilder =
assbuild.DefineDynamicModule(types[j].Module.Name);
TypeBuilder myTypeBuilder = myModuleBuilder.DefineType(t.Name,
TypeAttributes.Public);
MethodBuilder myMethod = myTypeBuilder.DefineMethod(mi.Name,
MethodAttributes.Public, CallingConventions.Standard, null,
myMethodArgs);
ILGenerator methodIL = myMethod.GetILGenerator();
methodIL.EmitWriteLine("Trace method: " + mi.Name);
methodIL.Emit(OpCodes.Nop,
mi.GetMethodBody().GetILAsByteArray().ToString());
types[j] = myTypeBuilder.CreateType();
I had hoped that the line
types[j]=myTypeBuilder.CreateType();
but when I try to use objects of this type, the logging statement does
not appear. Is what I'm trying to do even possible?