Reflection - get a list of method calls inside a lambda expression

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

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

Is it possible?

Thanks!

+5
source share
5 answers

, Expression<Action> Action. , , , . - ResolveMethod ( Invoke). , protobuf-net RPC lambdas.

+5


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<Action> 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<Action>)(() => Create(null, 0)));
}

}

>
+2
static MethodInfo GetMethodInfo<T>(Expression<Func<T>> expression)
{
    return ((MethodCallExpression)expression.Body).Method;
}
+1
+1

, . . , , .

, , IL . . IL- , , . , .

. -. lambda .

http://msdn.microsoft.com/en-us/library/bb397951.aspx

0

All Articles