gpt4 book ai didi

c# - 使用反射调用 Enumerable.Where(或其他重载的泛型方法)

转载 作者:太空狗 更新时间:2023-10-30 00:56:31 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com