5

我有以下 C# 代码:

public static double f(double x1, double x2 = 1)
{
    return x1 * x2;
}

这里是 IL 代码(ILSpy):

.method public hidebysig static 
    float64 f (
        float64 x1,
        [opt] float64 x2
    ) cil managed 
{
    .param [2] = float64(1)
    // Method begins at RVA 0x20c6
    // Code size 4 (0x4)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: mul
    IL_0003: ret
} // end of method A::f

如何使用System.Reflection.Emit或更好地使用Mono.Cecil获得它?

4

1 回答 1

4

如果我想做一些事情,我通常会使用预期的代码Mono.Cecil创建一个类/方法。C#然后我检查它(确保你在发布模式下运行它)Mono.Cecil并重新创建它。

所以你需要一个MethodDefinition带有name,attributesreturnType参数的。名称:“f”

您的方法的属性是:Mono.Cecil.MethodAttributes.FamANDAssem | Mono.Cecil.MethodAttributes.Family | Mono.Cecil.MethodAttributes.Static | Mono.Cecil.MethodAttributes.HideBySig

以及返回类型(类型Mono.Cecil.TypeReference为 as System.Double

至于参数,ParameterDefinition您可以添加两个target.Parameters.Add()

您的参数之一具有默认值,因此其属性必须是Mono.Cecil.ParameterAttributes.Optional | Mono.Cecil.ParameterAttributes.HasDefault 并且Constant设置为1.0(在您的情况下)

现在对于方法体:

target.Body.GetILProcessor();  // target is your `MethodDefinition` object.

检查来自 的说明后target.Body.Instructions,我们看到以下代码:

IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: mul
IL_0003: stloc.0
IL_0004: br.s IL_0007
IL_0005: ldloc.0
IL_0007: ret

所以只需按正确的顺序添加代码

 processor.Append(OpCodes.Ldarg_0);

之后,将您的注入/保存MethodDefinition到相应的程序集。

我的装配检查器代码如下所示:

 private static void EnumerateAssembly(AssemblyDefinition assembly)
        {
            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.GetAllTypes())
                {
                    foreach (var field in type.Fields)
                    {
                        Debug.Print(field.ToString());
                    }
                    foreach (var method in type.Methods)
                    {
                        Debug.Print(method.ToString());
                        foreach (var instruction in method.Body.Instructions)
                        {
                            Debug.Print(instruction.ToString());
                        }
                    }
                }
            }
        }
于 2012-10-12T09:06:53.213 回答