使用反射调用Enumerable.Where(或其他重载的通用方法) [英] Invoke Enumerable.Where (or other overloaded generic method) using reflection

查看:178
本文介绍了使用反射调用Enumerable.Where(或其他重载的通用方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Enumerable类中的"Where"方法有2个重载(或方法签名):

There are 2 overloads (or method signatures) of the "Where" method in Enumerable class:

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",所以我尝试通过参数来区分:

throws an exception stating an ambiguous match because, of course, there is more than one method with the name "Where", so I tried to differentiate by the parameters:

var types = new[] { 
    typeof(IEnumerable<>), 
    typeof(Func<,>)};
var where = typeof(Enumerable).GetMethod("Where", types);

但是这与任何一个方法签名都不匹配,我不确定为什么.

This however doesn't match either of the method signatures, and I'm not sure why.

通用问题:如何通过反射调用重载的通用方法,而又不遍历具有相同名称的类中的所有方法(即,使用System.Type.GetMethod(System.String,System.Type [])?

Generalized question: How do you invoke an overloaded generic method via reflection without iterating over all the methods in the class w/ the same name (i.e., using System.Type.GetMethod(System.String, System.Type[])?

请帮助我修复它!谢谢!

Please help me fix it! Thanks!

推荐答案

您不能仅使用 GetMethod()完成此操作,因为它对泛型有局限性.这就是正确使用 GetMethod()的方式.

You can't accomplish this with only GetMethod() because it has limitations with generics. This is how you would do it with GetMethod() properly.

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 ,因为它已经包含了 Where< TSource> 的两个 MethodInfo 定义.

The best way is to just iterate over members since it already contains both MethodInfo definitions for Where<TSource>.

这篇关于使用反射调用Enumerable.Where(或其他重载的通用方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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