有没有得到开放泛型方法的MethodInfo的好办法?好办法、方法、MethodInfo

由网友(时光让笑着的人哭了)分享简介:考虑型像这样的public interface IHaveGenericMethod{T1 Method(T1 parm);T2 Method(T1 parm);int Method2(int parm);}我如何获得的MethodInfo为它的方法呢?对于一个普通的非泛型方法,如方法2,...

考虑型像这样的

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.

阅读全文

相关推荐

最新文章