How to call a generic method if I only have an instance of the type?

class A { public static void M<T>() { ... } } ... Type type = GetSomeType(); 

Then I need to call AM<T>() where type == typeof(T) .
Reflection?

+4
source share
2 answers

Yes, you need a reflection. For instance:

 var method = typeof(A).GetMethod("M"); var generic = method.MakeGenericMethod(type); generic.Invoke(null, null); 
+6
source

Since the type is known at run time, you need to use reflection:

 Type type = GetSomeType(); var m = typeof(A) .GetMethod("M", BindingFlags.Static | BindingFlags.Public) .MakeGenericMethod(type); m.Invoke(null, null); 
+4
source

All Articles