mardi 19 février 2019

Calling generic method with constraints using reflection

I use Reflection to retrieve the methodInfo from a generic method:

public abstract class BaseIdea {}    

public class ModuleBaseLogic {
  public void Sponsor<T>(int id) {
    // Do something
  }
}

public class Caller {
  protected static MethodInfo GetMethod<T>(Expression<Action<T>> expr)
  {
    return ((MethodCallExpression)expr.Body).Method.GetGenericMethodDefinition();
  }

  public Caller() { 
    MethodInfo method = GetMethod<ModuleBaseLogic>(q => q.Sponsor<object>(id));
  }
}

This works fine. However if the method has constraints like:

public void Sponsor<T>(int id)  where T : BaseIdea, new() {
  // Do something
}

the q.Sponsor<object> (inside Caller) does not compile:

The Type "object" cannot be used as Type Parameter 'T' in the generic Type or method 'ModuleBaseLogic.Sponsor(int)' There is no implicit reference conversion from 'object' to 'BaseIdea'.

I tried replacing it by q.Sponsor<BaseIdea> but that doesn't work either





Aucun commentaire:

Enregistrer un commentaire