问题描述
大家好:最近在使用mono.cecil做代码注入,在System.Data.dll中的SqlConnection类的Open方法最前面插入Console,WriteLine("runOpen");但是启动测试代码去运行Open方法是并没有在控制台显示“runOpen”,又用mono.cecil对Open方法做改动,都没效果。AssemblyDefinitionasm=AssemblyDefinition.ReadAssembly("F:\System.Data.dll");foreach(TypeDefinitiontypeinasm.MainModule.Types){//if(type.Name.Equals("MySqlConnection")){foreach(MethodDefinitionmethodintype.Methods){//if(method.Name=="Open"){varilProcessor=method.Body.GetILProcessor();varfirstInstruction=ilProcessor.Body.Instructions[0];InstructioninsStr=ilProcessor.Create(OpCodes.Ldstr,"runOpen");ilProcessor.InsertBefore(firstInstruction,insStr);MethodReferencerefernce=asm.MainModule.ImportReference(typeof(Console).GetMethod("WriteLine",newType[]{typeof(string)}));InstructioninsCall=ilProcessor.Create(OpCodes.Call,refernce);ilProcessor.InsertAfter(insStr,insCall);}}//endforMethodDefinition}}//endforTypeDefinitionasm.Write("F:\System.Data.dll");用ILSpy查看System.Data.dll,确实有插入的代码,再调试时,运行到Console,WriteLine("runOpen");却并没效果。希望能指点一二。谢谢