开发者

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

开发者 https://www.devze.com 2023-02-01 07:25 出处:网络
I was wondering if someone mig开发者_开发问答ht be able to demonstrate how to use Type\'s GetMethod() method to retrieve a MethodInfo object for the following signature:

I was wondering if someone mig开发者_开发问答ht be able to demonstrate how to use Type's GetMethod() method to retrieve a MethodInfo object for the following signature:

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

Thanks,

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<IInterface2>)
                            )
                            .Single();

Note that you must then 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'm assuming:

class Class {
    public static void StaticMethod<T>(
        T arg1,
        IInterface1 arg2,
        IEnumerable<IInterface2> arg3
    ) { }
}


Type[] types = new Type[]{typeof(ClassUsedForTypeArgument)};
var info = typeof(Class).getMethod("StaticMethod").MakeGenericMethod(types);

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

Edit: If you just want the generic method info, without instantiating it with the type argument, you can do the following.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号