.net - 有没有一种获取开放泛型方法的 MethodInfo 的好方法?

标签 .net reflection metaprogramming

考虑像这样的类型

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

如何获取其方法的 methodInfo? 对于常规的非泛型方法,比如 method2,我可以使用

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

但是对于泛型方法,我不能,因为它的参数本身不是类型。 那么,我该怎么做呢? 我知道我可以打电话

typeof(IHaveGenericMethod).GetMethods()

获取该类型的所有方法,然后遍历该集合并进行一些匹配,但是很丑陋。有没有更好的办法?

最佳答案

请务必查看 MSDN 页面“Reflection and Generic Types”。

since it's parameters are not types per-se

其实我觉得是因为你要查询类型参数,但是你可以提供给GetMethod()的类型列表不是针对类型参数的。

此外,请记住,选择泛型方法的“方法组”所需要做的就是了解泛型类型参数的数量。所以你可以数一数。

then iterate

不要迭代,查询:

       var mi = from mi in typeof(IHaveGenericMethod).GetMethods()
                where mi.Name == "Method"
                where mi.IsGenericMethodDefinition
                where mi.GetGenericArguments().Length == 2
                select mi;

关于.net - 有没有一种获取开放泛型方法的 MethodInfo 的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/433798/

相关文章:

c# - EF 代码优先 : Where can I find the SavingChanges Event?

c# - 系统.DllNotFoundException : Unable to load DLL 'SqlServerSpatial110.dll' : The specified module could not be found

java - 对使用反射的方法进行单元测试

reflection - 如何使用反射提取接口(interface)类型名称和包?

Ruby 元编程 : adding @variables to existing 'initialize' method (using class_eval)

scala - 如何在dotty宏中访问case类的参数列表

c# - 在没有 toUpper/toLower 的情况下大写/小写字符串的最有效方法

c# - 是否可以强制将所有 DateTime 属性建模为 DateTime2?

.net - 以编程方式访问 .net 中的调用堆栈

C++ 我怎样才能改进这个模板元程序来返回包含大小的数组?