有没有得到开放泛型方法的MethodInfo的好办法? [英] Is there a good way of getting MethodInfo of open generic method?

查看:124
本文介绍了有没有得到开放泛型方法的MethodInfo的好办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑型像这样的

public interface IHaveGenericMethod
{
   T1 Method<T1>(T1 parm);
   T2 Method<T1,T2>(T1 parm);
   int Method2(int parm);
}

我如何获得的MethodInfo为它的方法呢? 对于一个普通的非泛型方法,如方法2,我可以去与

How do I get a methodInfo for its methods? for a regular non-generic method, like method2, I can go with

typeof(IHaveGenericMethod).GetMethod("methodName",new Type[]{typeof(itsParameters)});

虽然一个通用的方法,我不能,因为它的参数是不是每本身的类型。 那么,我该怎么办呢? 我知道,我可以叫

for a generic method though, I can't, since it's parameters are not types per-se. So, how do I do that? I know that I can call

typeof(IHaveGenericMethod).GetMethods()

要获得该类型的所有方法,然后遍历该集合,并做一些配套,但它的丑陋。有没有更好的办法?

to get all methods of that type, and then iterate over that collection and do some matching, but it's ugly. Is there a better way?

推荐答案

那么,他们的的类型 - 不爽:

Well, they are types - of sorts:

    foreach (var method in typeof(IHaveGenericMethod).GetMethods())
    {
        Console.WriteLine(method.Name);
        if (method.IsGenericMethodDefinition)
        {
            foreach (Type type in method.GetGenericArguments())
            {
                Console.WriteLine("> " + type.Name);
            }
        }
    }

所以,你可以通过args来数检查,并检查签名。但是,没有清洁剂。

So you can check by the number of args, and check the signature. But nothing cleaner.

这篇关于有没有得到开放泛型方法的MethodInfo的好办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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