在任意IQueryable <T>上获取Count()LINQ扩展方法的MethodInfo

Mil*_*vic 8 c# linq iqueryable count

我有IQueryable <T>源,我想动态调用IQueryable <T> .Count().

所以,我需要在IQueryable中声明的Count方法的MethodInfo.

这是来自msdn的签名(在IQueryable <>中):

public static int Count<TSource>(
    this IQueryable<TSource> source
)
Run Code Online (Sandbox Code Playgroud)

这是我有多远:

Expression expr; //this is expression which holds my IQueryable<T>
MethodInfo mi = expr.Type.GetMethod("Count", BindingFlags.Static | BindingFlags.Public, null, new[] { expr.Type }, null); 
Run Code Online (Sandbox Code Playgroud)

但我的mi总是空的;

我也尝试过:

mi = typeof(IQueryable<>).GetMethod("Count", BindingFlags.Static | BindingFlags.Public, null, new[] { expr.Type }, null);
Run Code Online (Sandbox Code Playgroud)

但又是空的.

我的最终目标是:

Expression.Call(mi, expr);
Run Code Online (Sandbox Code Playgroud)

更新:这是我得到Sum Extension方法的方法:

MethodInfo sum = typeof(Queryable).GetMethod("Sum", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(IQueryable<decimal>) }, null);
Run Code Online (Sandbox Code Playgroud)

这是有效的,但这个Sum方法不是通用的.它虽然是静态的.

And*_*tan 9

你需要破解IQueryable<T>类型的泛型参数并使用它; 拥有该方法的类型也不是IQueryable<T>,它是Queryable- 如果你考虑它 - 接口不能有静态方法(好吧,正如评论者指出的那样,在C#中):).

此外,因为它是一种通用方法,所以您无法以您尝试的方式匹配参数:因为您需要传递泛型类型定义 IQuerable<TSource> - 不是泛型类型 IQueryable<int>或实际表达式.

相反,您可以在类型上查找名为"Count"的静态方法的单参数版本Queryable:

Type genericArgument = expr.GetGenericArguments()[0];

MethodInfo countMethod = typeof(Queryable)
              .GetMethods(BindingFlags.Static | BindingFlags.Public)
              //narrow the search before doing 'Single()'
              .Single(mi => mi.Name == "Count"
                         // this check technically not required, but more future proof
                         && mi.IsGenericMethodDefinition
                         && mi.GetParameters().Length == 1)
              .MakeGenericMethod(genericArgument);

//now you can bind to 'countMethod'
Run Code Online (Sandbox Code Playgroud)

20173月7日更新 - 很明显,框架中发生了一些变化,导致代码示例的原始版本停止工作 - 这是一个应该工作的更新版本

更进一步 - 方法的签名是:

public static int Count<TSource>(
  this IQueryable<TSource> source
)
Run Code Online (Sandbox Code Playgroud)

所以虽然参数类型是类型IQueryable<TSource>的泛型TSource- 因此你需要IQueryable<TSource>捕获你的表达式并抓住它的泛型参数.你还应该能够在这里看到我对这个参数的意思.