How to use typeof(object).GetMethod() with lambda

2019-06-08 04:39发布

How does one use Type.GetMethod() to get a method with lambda parameters? I'm trying to get the Queryable.Any method for a parameter of something like Func, using this:

typeof(Queryable).GetMethod("Any", new Type[]{typeof(Func<ObjType, bool>)})

but it keeps returning null.

标签: c# lambda
1条回答
\"骚年 ilove
2楼-- · 2019-06-08 05:09

There are four things wrong:

  • There's no such thing as a "lambda parameter". Lambda expressions are often used to provide arguments to methods, but they're converted into delegates or expression trees
  • You've missed off the first parameter of Queryable.Any - the IQueryable<T>
  • You're using Func<ObjType, bool> which is a delegate type, instead of Expression<Func<ObjType, bool>> which is an expression tree type
  • You can't get at generic methods in quite that way, unfortunately.

You want:

var generic = typeof(Queryable).GetMethods()
                               .Where(m => m.Name == "Any")
                               .Where(m => m.GetParameters().Length == 2)
                               .Single();
var constructed = generic.MakeGenericMethod(typeof(ObjType));

That should get you the relevant Any method. It's not clear what you're then going to do with it.

查看更多
登录 后发表回答