如何获得“何处"的正确方法信息?扩展方法 [英] How to get the correct MethodInfo for "Where" extension method

查看:59
本文介绍了如何获得“何处"的正确方法信息?扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用反射返回正确的"Where"扩展方法,以构建自定义表达式.我尝试了几种方法,但最接近的方法抛出了异常:"mscorlib.dll中发生了'System.Reflection.AmbiguousMatchException'类型的未处理异常"

I am trying to get return the correct "Where" extension method using reflection, in order to build a custom Expression. I have tried several ways but the closest I get, throws an exception: "An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dll"

我知道这是因为在Enumrable类中定义了两个Where方法-但是我该如何仅使用的谓词来返回Where方法

I know this is because there are two Where methods defined in the Enumrable class - but how can I return the Where method which using only just a predicate of

 Func<T, bool>. 

我目前所拥有的是:

var collectionType = typeof(TSub);
Type tIEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionType);

MethodInfo methodInfo =
        typeof(Enumerable)
        .GetMethod("Where")                
        .MakeGenericMethod(collectionType);

我也尝试过(此返回null):

I have also tried (this one returns null):

MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", new[] { typeof(TSub )});

和(还返回null)

 MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", new[] { collectionType })

和(此返回相同的模棱两可的异常)

and (this one returns the same Ambiguous Exception)

MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", BindingFlags.Public |      BindingFlags.Static)

任何人都可以帮忙吗?

谢谢

推荐答案

在我看来,当前的答案(包括已接受的答案)比必要的要复杂得多.如果您具有在编译时可以使用的 T 类型,则可以这样获得 MethodInfo :

In my opinion, the current answers, including the accepted one, are far more complicated than necessary. If you have a type T that you can use at compile time, you can get the MethodInfo like so:

Func<IEnumerable<T>, Func<T, bool>, IEnumerable<T>> whereDelegate = Enumerable.Where;
MethodInfo whereMethodInfo = whereDelegate.Method;

作为一种额外的奖励,这是强烈键入的.如果可以解析 Enumerable.Where ,它将只编译 ,而不是寻找字符串"Where" 的任何东西:如果您不小心输入"Wehre" 很好,但是在运行时会失败.

As an extra bonus, this is strongly typed. It will compile only if the Enumerable.Where can be resolved, as opposed to anything that looks for a string "Where": that would compile just fine if you accidentally type "Wehre" instead, but would fail at runtime.

这篇关于如何获得“何处"的正确方法信息?扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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