【问题标题】:How to invoke IEnumerable<T>.Any() method via MethodInfo如何通过 MethodInfo 调用 IEnumerable<T>.Any() 方法
【发布时间】:2019-04-09 20:23:31
【问题描述】:

我想通过 MethodInfo 调用IEnumerable&lt;T&gt;.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&lt;int&gt;——想想Any&lt;...&gt;()应该返回什么。
  • 您到底想达到什么目的(高级概述)? Dynamic LINQ 会帮助实现这个目标吗?
  • 你不是已经问过这个问题了吗? stackoverflow.com/q/55586426/491907

标签: c# generics reflection


【解决方案1】:

此代码有效:

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 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多