Mono Cecil,方法和指令插入

Mono Cecil, method and instruction insertion

我在添加方法并使用说明填充它时遇到问题。我找到了所需的类型,添加的方法没有问题,但是当我添加对 WriteLine 的调用时它不起作用。

    foreach (TypeDefinition type in assembly.MainModule.Types)
        {
            if (type.Name == "ClassB")
            {
                //TypeReference returntype = assembly.MainModule.Import(typeof(void));
                MethodDefinition met = new MethodDefinition("Test", 
                    MethodAttributes.Private | MethodAttributes.Static, 
                    assembly.MainModule.TypeSystem.Void);
                type.Methods.Add(met);

                ILProcessor worker = met.Body.GetILProcessor();
                Instruction msg = worker.Create(OpCodes.Ldstr, "Hello!");
                MethodReference writeline = assembly.MainModule.Import(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
                met.Body.Instructions.Insert(0, msg);
                met.Body.Instructions.Insert(1, Instruction.Create(OpCodes.Call, writeline));
            }

当我反编译代码时,我得到“// 问题:无法反编译该方法。”在方法体中(我使用的是 dotPeek)。在程序集中添加对现有方法的调用非常好——它是可见的并且可以正确执行。 运行.

时不会抛出任何错误

即使您的方法无效,您也应该在方法结束之前插入一条 OpCodes.Ret 指令,如下所示:

...
met.Body.Instructions.Insert(0, msg);
met.Body.Instructions.Insert(1,
    Instruction.Create(OpCodes.Call, writeline));
met.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));