Get MethodInfo for lambda expression

I know I'm wondering, but just for punches, is it possible to get MethodInfo to express lambda?

I'm for something like this:

(Func<int, string>(i => i.ToString())).MethodInfo

UPDATE I want to get information about the method regardless of whether the lamda body is a method invocation expression or not, that is, regardless of what type of expression the lambda body is.

So for example

It 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 this to work:

 var intExpression = Expression.Constant(2); Expression<Func<int, Dog>> conversionExpression = i => new Dog(); var convertExpression5 = Expression.ConvertChecked(intExpression, typeof(Dog), /*...???... */); 
+5
source share
2 answers

You are very close :)

You can do something like this:

 MethodInfo meth = (new Func<int, string>(i => i.ToString())).Method; 

Note. This can be a problem if you have several "subscribers" for the delegate instance.

MSDN: http://msdn2.microsoft.com/en-us/library/system.delegate.method

+6
source

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; 
+2
source

Source: https://habr.com/ru/post/1210444/


All Articles