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), /*...???... */);
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.
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.method
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With