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

前端 未结 5 1531
迷失自我
迷失自我 2021-01-13 08:32

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)

5条回答
  •  心在旅途
    2021-01-13 09:35

    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)));
        }
    }
    

提交回复
热议问题