使用Mono.Cecil导入方法
请用方法导入帮我。 我想编织程序集和从另一个程序集中定义的基类注入方法调用引用(实际上它是定义编织代码的程序集)。
private void InsertCallSetReference() { //Get the load instruction to replace var ilProcessor = Property.SetMethod.Body.GetILProcessor(); var argumentLoadInstructions = ilProcessor.Body.Instructions.ToList(); MethodReference methodReference = ImportMethod("SetReference"); foreach (var instruction in argumentLoadInstructions) { if (instruction.OpCode == OpCodes.Stfld) { ilProcessor.InsertAfter(instruction, ilProcessor.Create(OpCodes.Call, methodReference)); ilProcessor.InsertAfter(instruction, ilProcessor.Create(OpCodes.Ldarg_1)); ilProcessor.InsertAfter(instruction, ilProcessor.Create(OpCodes.Ldstr, DBFieldName)); ilProcessor.InsertAfter(instruction, ilProcessor.Create(OpCodes.Ldarg_0)); ilProcessor.Remove(instruction); break; } } }
方法导入代码工作正常并返回方法引用
private MethodReference ImportMethod(string name) { var type = MongoConnectModule.Import(typeof(BaseDataObject)); return MongoConnectModule.Import(type.Resolve().Methods.First(m => m.Name == name)); }
但在AssemblyDefinition Write调用之后它会抛出一个错误:
C: dev MongoConnect WeavingTaskTest Weaving CodeWeaving.targets(32,5):错误MSB4018:System.ArgumentException:声明成员’System.Void MongoConnect.BaseDataObject :: SetProperty(System.String,System.Object)’在另一个模块中,需要导入
_assemblyDefinition.Write(_assemblyPath, new WriterParameters() { WriteSymbols = true, SymbolWriterProvider = debugWriterProvider });
知道我怎么能这样做吗?
我找到了解决方案。 原因很有趣。
必须从我们想要修改的当前模块调用Module.Import()
方法,而不是定义方法的模块。 从原始文档中不清楚。
例如,我们想要将Referenced.dll
程序Main.dll
定义的一些方法添加到我们的Main.dll
程序Main.dll
。 然后我们必须找到Main.dll
程序集的主模块,然后调用MainModule.Import(methodFromReferencedAssembly);
上述就是C#学习教程:使用Mono.Cecil导入方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1042126.html