1. 安装Mono.Cecil
2. 创建一个測试项目:
加入測试方法:
这种方法的返回值会被动态重写.
public class Class1 { public static string Test() { return "ok"; } }
3. code Injection 代码:
var path = @"XXinDebugClassLibrary1.dll"; var assembly = AssemblyDefinition.ReadAssembly (path); var type =assembly.MainModule.GetType("ClassLibrary1.Class1"); var foundMethod = type.GetMethods().First(m => m.Name =="Test"); ////清空当前方法指令 foundMethod.Body.Instructions.Clear(); ////获得当前IL的指令执行器 var worker = foundMethod.Body.GetILProcessor(); ////改动返回值 Instruction ins1 = worker.Create(OpCodes.Ldstr, "will be changed onnext time run"); Instruction ins2 = worker.Create(OpCodes.Ret); worker.Append(ins1); worker.Append(ins2); ////保存DLL文件 assembly.Write(path); ////下次调用就会看到(由于新保存的DLL下次才干载入到) Console.WriteLine(Class1.Test()); Console.Read();
4. 执行查看结果