获取Lambda表达式的MethodInfo [英] Get MethodInfo for a lambda expression
问题描述
我知道我要问怪异的事,但只是为了踢球,是否有可能获得 MethodInfo
作为lambda表达式?
I know I am asking the bizarre but just for kicks, is it possible to get the MethodInfo
for a lambda expression?
我在追求类似这样的东西:
I am after something like this:
(Func< int,string>(i => i.ToString() ))。MethodInfo
UPDATE
无论主体是否要获取方法信息lamda的值是否为方法调用表达式,即,不管lambda的主体是哪种表达式类型。
UPDATE I want to get the method info regardless of whether the body of the lamda is a method call expression or not, i.e. regardless of what type of expression the body of the lambda is.
因此,例如,
这可能有用。
var intExpression = Expression.Constant(2);
Expression<Func<int, Dog>> conversionExpression = i => Program.GetNewDog(i);
var convertExpression5 = Expression.ConvertChecked(intExpression, typeof(Dog), ((MethodCallExpression)(conversionExpression.Body)).Method);
class Program
{
static Dog GetNewDog(int i)
{
return new Dog();
}
}
但是我也希望它能起作用:
But I want even this to work:
var intExpression = Expression.Constant(2);
Expression<Func<int, Dog>> conversionExpression = i => new Dog();
var convertExpression5 = Expression.ConvertChecked(intExpression, typeof(Dog), /*...???... */);
推荐答案
您非常接近:)
您可以执行以下操作:
MethodInfo meth = (new Func<int, string>(i => i.ToString())).Method;
注意:如果您有多个订阅者
Note: This might have problems if you have multiple 'subscribers' to a delegate instance.
MSDN: http://msdn2.microsoft.com/en-us/library/system.delegate.method
这篇关于获取Lambda表达式的MethodInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!