Get MethodInfo for a lambda expression

2019-02-23 04:11发布

问题:

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 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.

So, for e.g.

This might work.

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), /*...???... */);

回答1:

You are quite close :)

You can do something like this:

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



回答2:

Using the System.Linq.Expressions namespace, you can do the following.

Expression<Func<int, string>> expression = i => i.ToString();
MethodInfo method = ((MethodCallExpression)expression.Body).Method;