samedi 6 avril 2019

How to call a generic method at runtime in typesafe way

I'm trying to call a generic method at run time, and have working code. However, I was wondering if there was a better way of getting the method info, as should i change the method name, it will break.

public int Handle<T>(CreateCodeModel obj) where T : CodeModel
{
     //Create code here...
}

//codeType is selected by user.
public int Handle(CreateCodeModel obj, Type codeType)
{

    MethodInfo method = this.GetType().GetMethod("Handle");
    //MethodInfo method = this.GetType().GetMethods()
            .Where(mi => mi.IsGenericMethod && mi.Name == "Handle").First();

    MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { codeType });
    return (int)genericMethod.Invoke(this, new object[] { obj });

}

I had hoped there was a nicer way of doing this, perhaps using actions to get the method info, but then I still need to provide a type, e.g.

Action<CreateCodeModel> h = (x) => Handle(x);
MethodInfo method = h.Method;





Aucun commentaire:

Enregistrer un commentaire