【发布时间】:2019-04-09 20:23:31
【问题描述】:
我想通过 MethodInfo 调用IEnumerable<T>.Any()。
List<int> list = new List<int>();
for (int i = 0; i < 10; i++)
{
list.Add(i);
}
Func<C, bool> func = c => c.Value > 10;
Expression<Func<int, bool>> exp = (Expression<Func<int, bool>>)(c => c > 10);
MethodInfo[] mis = typeof(System.Linq.Enumerable).GetMethods();
MethodInfo miAny = mis.FirstOrDefault(d => d.Name == "Any" && d.GetParameters().Count()==2);
var gf = miAny.MakeGenericMethod(new Type[] {list.GetType() });
var re = gf.Invoke(null, new object[] {list,func });
但是编译器在var re = gf.Invoke(null, new object[] {list,func });报错,比如说
`can't convert “System.Collections.Generic.List`1[System.Int32]” to “System.Collections.Generic.IEnumerable`1[System.Collections.Generic.List`1[System.Int32]]”`。
如何修复此错误?
【问题讨论】:
-
您的
MakeGenericMethod错误。你想要的泛型方法的类型参数是int,而不是List<int>——想想Any<...>()应该返回什么。 -
您到底想达到什么目的(高级概述)? Dynamic LINQ 会帮助实现这个目标吗?
-
你不是已经问过这个问题了吗? stackoverflow.com/q/55586426/491907
标签: c# generics reflection