如何通过MethodInfo

时间:2019-04-09 07:49:18

标签: c# generics reflection

我想通过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]]”`。

如何修复此错误?

1 个答案:

答案 0 :(得分:0)

此代码有效:

List<int> list = new List<int>();
for (int i = 0; i< 12; i++)
{
    list.Add(i);
}

MethodInfo[] mis = typeof(System.Linq.Enumerable).GetMethods();
MethodInfo miAny = mis.FirstOrDefault(d => d.Name == "Any" && d.GetParameters().Count() == 2);
Func<int, bool> func = c => c > 10;
MethodInfo gf = miAny.MakeGenericMethod(new Type[] { typeof(int) });
bool any = (bool)gf.Invoke(null, new object[] { list, func });