2

我有以下代码:

    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));
    }

运行后,得到如下错误:

因为它的签名或安全透明与委托类型的签名或安全透明不兼容。

以下正常工作:

  static RefAction CreateRefGenerator(){
        Type[] types = { typeof(Int32).MakeByRefType() };
        ...
  }
4

1 回答 1

6

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

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


您的 il 代码中也可能存在错误:Afaik 动态方法始终是静态的,因此第一个显式参数可以在索引零而不是索引处找到。

于 2017-05-17T06:14:40.200 回答