Here\'s my class:
public class MyClass
{
public void MyMethod(T a)
{
}
public void MyMethod(int a)
{
}
}
The only way I was able to do this was to use GetGenericTypeDefinition
with IsGenericParameter
. In the generic type definition, one method will have IsGenericParameter
set to true on the parameter. However, for closed types none of the parameters will have this as true. Then, you can't use the MethodInfo
from the generic type definition to invoke the method, so I stored the index and used that to lookup the corresponding MethodInfo
in the closed type.
public class Program
{
public static void Main(string[] args)
{
bool invokeGeneric = true;
MyClass b = new MyClass();
var type = b.GetType().GetGenericTypeDefinition();
int index = 0;
foreach(var mi in type.GetMethods().Where(mi => mi.Name == "MyMethod"))
{
if (mi.GetParameters()[0].ParameterType.IsGenericParameter == invokeGeneric)
{
break;
}
index++;
}
var method = b.GetType().GetMethods().Where(mi => mi.Name == "MyMethod").ElementAt(index);
method.Invoke(b, new object[] { 1 });
}
}
public class MyClass
{
public void MyMethod(T a)
{
Console.WriteLine("In generic method");
}
public void MyMethod(int a)
{
Console.WriteLine("In non-generic method");
}
}