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.GetExe cutingAssembly( );
Type[] types = currentAssembly .GetTypes();
....//other unrelated code removed...
AppDomain appDomain = AppDomain.Curre ntDomain;
AssemblyBuilder assbuild =
appDomain.Defin eDynamicAssembl y(currentAssemb ly.GetName(),
AssemblyBuilder Access.Run);
//types[j] is the index in types of the type I need to modify.
ModuleBuilder myModuleBuilder =
assbuild.Define DynamicModule(t ypes[j].Module.Name);
TypeBuilder myTypeBuilder = myModuleBuilder .DefineType(t.N ame,
TypeAttributes. Public);
MethodBuilder myMethod = myTypeBuilder.D efineMethod(mi. Name,
MethodAttribute s.Public, CallingConventi ons.Standard, null,
myMethodArgs);
ILGenerator methodIL = myMethod.GetILG enerator();
methodIL.EmitWr iteLine("Trace method: " + mi.Name);
methodIL.Emit(O pCodes.Nop,
mi.GetMethodBod y().GetILAsByte Array().ToStrin g());
types[j] = myTypeBuilder.C reateType();
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?
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.GetExe cutingAssembly( );
Type[] types = currentAssembly .GetTypes();
....//other unrelated code removed...
AppDomain appDomain = AppDomain.Curre ntDomain;
AssemblyBuilder assbuild =
appDomain.Defin eDynamicAssembl y(currentAssemb ly.GetName(),
AssemblyBuilder Access.Run);
//types[j] is the index in types of the type I need to modify.
ModuleBuilder myModuleBuilder =
assbuild.Define DynamicModule(t ypes[j].Module.Name);
TypeBuilder myTypeBuilder = myModuleBuilder .DefineType(t.N ame,
TypeAttributes. Public);
MethodBuilder myMethod = myTypeBuilder.D efineMethod(mi. Name,
MethodAttribute s.Public, CallingConventi ons.Standard, null,
myMethodArgs);
ILGenerator methodIL = myMethod.GetILG enerator();
methodIL.EmitWr iteLine("Trace method: " + mi.Name);
methodIL.Emit(O pCodes.Nop,
mi.GetMethodBod y().GetILAsByte Array().ToStrin g());
types[j] = myTypeBuilder.C reateType();
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?
Comment