C# Mono-Cecil、方法和指令插入
我在添加方法并用指令填充它时遇到问题。我找到了所需的类型,添加了没有问题的方法,但是当我添加对WriteLine的调用时,它就不起作用了C# Mono-Cecil、方法和指令插入,c#,mono,C#,Mono,我在添加方法并用指令填充它时遇到问题。我找到了所需的类型,添加了没有问题的方法,但是当我添加对WriteLine的调用时,它就不起作用了 foreach (TypeDefinition type in assembly.MainModule.Types) { if (type.Name == "ClassB") { //TypeReference returntype = assembly.M
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));
}
当我反编译代码时,我在方法体中得到“//问题:无法反编译该方法”。将调用添加到程序集中已经存在的方法中效果非常好——它是可见的,并且执行正确。它在运行时不会抛出任何错误。即使您的方法无效,也应在方法结束前插入
操作码.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));
事实上,这一行让它成功了。非常感谢您的帮助。或许可以看看这个:)