如何在DynamicMethod Emit中表示typeof(Int32&)类型

Ken*_*nny 1 c# cil dynamicmethod emit

我有以下代码:

    delegate void RefAction(ref Int32 i);// use ref keyword
    static RefAction CreateRefGenerator(){
        // How to represent typeof(Int32&)type in here??
        Type[] types ={ typeof(Int32)};
        var dm = new DynamicMethod("RefAction"+Guid.NewGuid().ToString(), null, types, true);
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Nop);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldc_I4_S,10);
        il.Emit(OpCodes.Stind_I4);
        il.Emit(OpCodes.Ret);

        return (RefAction)dm.CreateDelegate(typeof(RefAction));
    }
Run Code Online (Sandbox Code Playgroud)

运行后,得到以下错误:

因为其签名或安全透明性与委托类型的签名或安全透明性不兼容.

以下正常工作:

  static RefAction CreateRefGenerator(){
        Type[] types = { typeof(Int32).MakeByRefType() };
        ...
  }
Run Code Online (Sandbox Code Playgroud)

the*_*nyy 5

您必须使用该Type.MakeByRefType方法来创建您的ref类型.

返回一个Type对象,该对象表示作为ref参数传递时的当前类型


你的il代码中可能还有一个错误:Afaik动态方法总是静态的,因此第一个显式参数可以在索引零处找到而不是一个.