Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection - Get the list of method calls inside a lambda expression

I am trying to find a way to get the list of method calls inside a lambda expression in C# 3.5. For instance, in the code below, I would like to method LookAtThis(Action a) to analyze the content of the lambda expression. In other words, I want LookAtThis to return me the MethodInfo object of Create.

LookAtThis(() => Create(null, 0));

Is it possible?

Thanks!

like image 981
Martin Avatar asked Apr 04 '09 13:04

Martin


2 Answers

This is fairly easy as long as you use Expression<Action> instead of Action. For full code, including how to get the actual values implied, see here - in particular ResolveMethod (and how it is used by Invoke). This is the code I use in protobuf-net to do RPC based on lambdas.

like image 66
Marc Gravell Avatar answered Oct 03 '22 19:10

Marc Gravell


using System;
using System.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Linq.Expressions;

class Program
{
    static void Create(object o, int n) { Debug.Print("Create!"); }

    static void LookAtThis(Expression expression)
    {
        //inspect:
        MethodInfo method = ((MethodCallExpression)expression.Body).Method;
        Debug.Print("Method = '{0}'", method.Name);

        //execute:
        Action action = expression.Compile();
        action();
    }

    static void Main(string[] args)
    {
        LookAtThis((Expression)(() => Create(null, 0)));
    }
}
like image 21
ILoveFortran Avatar answered Oct 03 '22 19:10

ILoveFortran