如何使用拉姆达参数的typeof(对象).GetMethod() [英] How to use typeof(object).GetMethod() with lambda parameter
本文介绍了如何使用拉姆达参数的typeof(对象).GetMethod()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个人如何使用Type.GetMethod()来获得与拉姆达参数的方法?我试图让Queryable.Any方法对于像函数功能参数,使用这样的:
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>)})
但它一直返回null
but it keeps returning null.
推荐答案
有四件事情错了:
- 有一个拉姆达参数没有这样的事。 Lambda表达式通常被用来提供的参数应用于方法,但它们转换成委托或表达式树
- 您已经错过了<$的第一个参数C $ C> Queryable.Any - 在
的IQueryable< T>
- 您正在使用
Func键< OBJTYPE,布尔>
这是不是表达℃的委托类型;函数功能:LT; OBJTYPE,布尔>>
这是表达式目录树类型 - 您不能在相当那样泛型方法得到的,很遗憾。
- 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
- theIQueryable<T>
- You're using
Func<ObjType, bool>
which is a delegate type, instead ofExpression<Func<ObjType, bool>>
which is an expression tree type - You can't get at generic methods in quite that way, unfortunately.
您想要的:
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.
这篇关于如何使用拉姆达参数的typeof(对象).GetMethod()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文