我试图使用反射返回正确的“ Where”扩展方法,以构建自定义表达式。我已经尝试了几种方法,但是得到的最接近的方法引发了异常:“ mscorlib.dll中发生了'System.Reflection.AmbiguousMatchException'类型的未处理异常”
我知道这是因为在Enumrable类中定义了两个Where方法-但是我怎么能只使用谓词来返回Where方法
Func<T, bool>.
我目前所拥有的是:
var collectionType = typeof(TSub);
Type tIEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionType);
MethodInfo methodInfo =
typeof(Enumerable)
.GetMethod("Where")
.MakeGenericMethod(collectionType);
我也试过了(这个返回null):
MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", new[] { typeof(TSub )});
和(还返回null)
MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", new[] { collectionType })
和(此返回相同的歧义异常)
MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", BindingFlags.Public | BindingFlags.Static)
任何人都可以帮忙吗?
谢谢
我认为,当前的答案(包括已接受的答案)比必要的要复杂得多。如果您有T
可以在编译时使用的类型,则可以这样获得MethodInfo
:
Func<IEnumerable<T>, Func<T, bool>, IEnumerable<T>> whereDelegate = Enumerable.Where;
MethodInfo whereMethodInfo = whereDelegate.Method;
作为一种额外的奖励,这是强烈键入的。它只会在Enumerable.Where
可以解析的情况下进行编译,而不是寻找字符串的任何内容"Where"
:如果您不小心键入内容"Wehre"
,则可以正常编译,但在运行时会失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句