How to get the correct MethodInfo object when the class uses generics and general type parameters

I was wondering if anyone could demonstrate how to use the Type GetMethod () method to retrieve a MethodInfo object for the following signature:

Class.StaticMethod<T>(T arg1, IInterface1 arg2, IEnumerable<IInterface2> arg3) 

Thanks,

Xam

+8
generics reflection c #
source share
2 answers
 MethodInfo methodInfo = typeof(Class) .GetMethods( BindingFlags.Public | BindingFlags.Static ) .Where(m => m.Name == "StaticMethod") .Where(m => m.IsGenericMethod) .Where(m => m.GetGenericArguments().Length == 1) .Where(m => m.GetParameters().Length == 3) .Where(m => m.GetParameters()[0].ParameterType == m.GetGenericArguments()[0] && m.GetParameters()[1].ParameterType == typeof(IInterface1) && m.GetParameters()[2].ParameterType == typeof(IEnumerable<IInterface2>) ) .Single(); 

Please note that you must follow this with

 methodInfo = methodInfo.MakeGenericMethod(new Type[] { typeof(ConcreteType) }); 

to close the type, where ConcreteType is the type you want for the type parameter T

I suppose:

 class Class { public static void StaticMethod<T>( T arg1, IInterface1 arg2, IEnumerable<IInterface2> arg3 ) { } } 
+7
source share
 Type[] types = new Type[]{typeof(ClassUsedForTypeArgument)}; var info = typeof(Class).getMethod("StaticMethod").MakeGenericMethod(types); 

"information" contains what you want, if I'm not mistaken.

Edit: if you just want to get information about a generic method without creating it with a type argument, you can do the following.

 var info = typeof(Class).getMethod("StaticMethod"); 
0
source share

Source: https://habr.com/ru/post/650514/


All Articles