Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

referencing desired overloaded generic method

given

public Class Example
{

public static void Foo< T>(int ID){}

public static void Foo< T,U>(int ID){}

}

Questions:

  1. Is it correct to call this an "overloaded generic method"?
  2. How can either method be specified in creation of a MethodInfo object?

    Type exampleType = Type.GetType("fullyqualifiednameOfExample, namespaceOfExample");
    MethodInfo mi = exampleType.GetMethod("Foo", BindingFlags.Public|BindingFlags.Static, null, new Type[] {typeof(Type), typeof(Type) }, null);
    

argument 4 causes the compiler much displeasure

like image 301
sympatric greg Avatar asked Feb 25 '09 22:02

sympatric greg


1 Answers

I can't find a way of using GetMethod that would do what you want. But you can get all the methods and go through the list until you find the method that you want.

Remember you need to call MakeGenericMethod before you can actually use it.

var allMethods = typeof (Example).GetMethods(BindingFlags.Public | BindingFlags.Static);
MethodInfo foundMi = allMethods.FirstOrDefault(
    mi => mi.Name == "Foo" && mi.GetGenericArguments().Count() == 2);
if (foundMi != null)
{
    MethodInfo closedMi = foundMi.MakeGenericMethod(new Type[] {typeof (int), typeof (string)});
    Example example= new Example();
    closedMi.Invoke(example, new object[] { 5 });
}
like image 187
Ray Avatar answered Oct 21 '22 17:10

Ray