samedi 15 mai 2021

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

I want to create dynamic assembly with generic class:

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

  private Func<T> f;
}

So, I created class, added generic argument, set constraints and created delegate like this:

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

Then using IL generator I tried to emit calling Invoke method:

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

But I get NotSupportedException on GetMethod("Invoke") call. So, how to call this delegate using Emit?





Aucun commentaire:

Enregistrer un commentaire