如何得到正确的MethodInfo对象当一个类使用泛型和泛型类型参数 [英] How to get the correct MethodInfo object when a class uses generics and generic type parameters

查看:583
本文介绍了如何得到正确的MethodInfo对象当一个类使用泛型和泛型类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人也许能演示如何使用Type的实现getMethod()方法来检索以下签名的MethodInfo的对象:

  Class.StaticMethod< T>(T ARG1,IInterface1 ARG2,IEnumerable的< IInterface2>参数3)

谢谢,



XAM


解决方案

  MethodInfo的MethodInfo的= typeof运算(类)
.GetMethods(
BindingFlags.Public | BindingFlags.Static

。凡(M = GT; m.Name = =静态方法)
。凡(M = GT; m.IsGenericMethod)
。凡(M = GT; m.GetGenericArguments()。长度== 1)
。凡(M =方式> m.GetParameters()==长度3)
。凡(M = GT;
m.GetParameters()[0] == .ParameterType
m.GetGenericArguments() [0]&放大器;&放大器;
m.GetParameters()[1] .ParameterType ==
typeof运算(IInterface1)及和放大器;
m.GetParameters()[2] .ParameterType ==
的typeof(IEnumerable的&所述; IInterface2>)$ B $二)
。单();

请注意,您必须然后用



遵循这个

  MethodInfo的= methodInfo.MakeGenericMethod(新类型[] {typeof运算(ConcreteType)}); 



收类型,其中 ConcreteType 是你想要的类型参数 T 键入



我假设:

 类类{
公共静态无效STATICMETHOD< T>($ b $(b T)ARG1,
IInterface1 ARG2,
的IEnumerable< ; IInterface2> ARG3
){}
}


I was wondering if someone might 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
    ) { }
}

这篇关于如何得到正确的MethodInfo对象当一个类使用泛型和泛型类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆