mercredi 28 avril 2021

How do you get specific generic method overload from static class using reflection?

so I have a static class:

class static EnumHelper {
   public string GetCode<E>(E value) where E: struct {}

   public string GetCode<E>(E? value) where E: struct {}
}

however using:

typeof(EnumHelper).GetMethod("GetCode")

always returns this error:

System.Reflection.AmbiguousMatchException: Ambiguous match found.

However, i can't directly use the overload of GetMethod providing the "parameter types" because the parameter type are based upon the generic type argument defined in the method itself.

The goal is to:

//given parameter: T item
MethodInfo mi = typeof(EnumHelper).GetMehod("GetCode");
mi.MakeGenericMethod(typeof(T));
mi.Invoke(null, new object[] {item});

but I'm having trouble at the "GetMethod" part of this equation.

Thanks.





Aucun commentaire:

Enregistrer un commentaire