作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
Enumerable 类中的“Where”方法有 2 个重载(或方法签名):
namespace System.Linq {
public static class Enumerable {
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
}
所以
var where = typeof(Enumerable).GetMethod("Where")
抛出一个异常,指出一个不明确的匹配,因为,当然,有不止一个名为“Where”的方法,所以我试图通过参数来区分:
var types = new[] {
typeof(IEnumerable<>),
typeof(Func<,>)};
var where = typeof(Enumerable).GetMethod("Where", types);
然而,这与任何一个方法签名都不匹配,我不确定为什么。
一般性问题:如何通过反射调用重载的泛型方法,而无需迭代类中具有相同名称的所有方法(即,使用 System.Type.GetMethod(System.String, System.Type[]) ?
请帮我解决一下!谢谢!
最佳答案
您无法仅使用 GetMethod()
来完成此操作因为它对泛型有限制。这就是您使用 GetMethod()
的方式
Type enumerableType = typeof(Enumerable);
MemberInfo[] members = enumerableType.GetMember("Where*");
MethodInfo whereDef = (MethodInfo)members[0]; // Where<TSource>(IEnumerable<TSource, Func<TSource,Boolean>)
Type TSource = whereDef.GetGenericArguments()[0]; // TSource is the only generic argument
Type[] types = { typeof(IEnumerable<>).MakeGenericType(TSource), typeof(Func<,>).MakeGenericType(TSource, typeof(Boolean)) };
MethodInfo method = enumerableType.GetMethod("Where", types);
最好的方法就是遍历 members
因为它已经包含 MethodInfo
Where<TSource>
的定义.
关于c# - 使用反射调用 Enumerable.Where(或其他重载的泛型方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538462/
我是一名优秀的程序员,十分优秀!