在动态程序集中使用泛型参数调用委托 (func/action)

Call delegate (func/action) with generic argument in dynamic assembly

我想用泛型创建动态程序集class:

class TestClass<T> where T : new() {
  public T TestMethod() {
    return f();
  }

  private Func<T> f;
}

所以,我创建了 class,添加了通用参数,设置了约束并创建了这样的委托:

var fieldType = typeof(Func<>).MakeGenericType(TArg); 
// TArg = testClassBuilder.DefineGenericParameters("T")[0];

然后使用 IL 生成器我尝试调用 Invoke 方法:

ilGenerator.Emit(OpCodes.Callvirt, fieldType.GetMethod("Invoke"));

但我在 GetMethod("Invoke") 电话中接到 NotSupportedException。那么,如何使用 Emit 调用此委托?

您不能在 typeof(Func<>).MakeGenericType(TArg) 上调用 GetMethod,因为在这种情况下,TArg 是一个 GenericTypeParameterBuilder,而 Type 返回的对象是 MakeGenericType不知道如何获取相关方法

而是 use TypeBuilder.GetMethod 像这样:

ilGenerator.Emit(
    OpCodes.Callvirt,
    TypeBuilder.GetMethod(
        typeof(Func<>).MakeGenericType(genParam),
        typeof(Func<>).GetMethod("Invoke")
));