如何在 Mono.Cecil 中创建 Ldarg_S 指令?

How do I create Ldarg_S instruction in Mono.Cecil?

在Mono.Cecil中,使用Ldarg_S创建指令时,直接的做法:

Instruction.Create(OpCodes.Ldarg_S, 4);

不起作用,因为 Mono.Cecil expects the operand type to be OperandType.InlineI, while the operand type of OpCodes.Ldarg_S is ShortInlineArg. Instead, I need to use the Create (OpCode opcode, ParameterDefinition parameter) : Instruction 过载。

这需要初始化 ParameterDefinition,而 ParameterDefinition 又需要以下参数:

那些东西是什么?如何指定我只需要第四个(或第五个或第六个)参数?

深入研究了Mono.Cecil的源代码后,似乎无法生成像ldarg.s 4.

这样简单的指令。

相反,Mono.Cecil 的作用是它需要您指定 ParameterDefinition,然后将其与方法的参数列表匹配,以便找到实际索引。

最简单的方法就是用MethodDefinition.Parameters属性通过索引检索对应的传给Instruction.Create。可能,这种方法的目标是通过指定给定参数并让 Mono.Cecil 确定实际索引,使调用者更安全地管理参数。实际上,调用者确定实际索引可能有点棘手,尤其是在 ldarg.0 引用 this 而不是实际第一个参数的实例方法的情况下。