当类使用generics和generics类型参数时,如何获取正确的MethodInfo对象
我想知道是否有人能够演示如何使用Type的GetMethod()方法来检索以下签名的MethodInfo对象:
Class.StaticMethod(T arg1, IInterface1 arg2, IEnumerable arg3)
谢谢,
XAM
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) ) .Single();
请注意,您必须遵循此操作
methodInfo = methodInfo.MakeGenericMethod(new Type[] { typeof(ConcreteType) });
关闭ConcreteType
是类型参数T
所需类型的类型。
我假设:
class Class { public static void StaticMethod( T arg1, IInterface1 arg2, IEnumerable arg3 ) { } }
Type[] types = new Type[]{typeof(ClassUsedForTypeArgument)}; var info = typeof(Class).getMethod("StaticMethod").MakeGenericMethod(types);
如果我没有弄错的话,“信息”包含你想要的东西。
编辑:如果您只想要通用方法信息,而不使用type参数进行实例化,则可以执行以下操作。
var info = typeof(Class).getMethod("StaticMethod");