get end values from lambda expressions method parameters

后端 未结 5 1254
青春惊慌失措
青春惊慌失措 2020-12-10 15:48

basically I want to get the values of the parameters of a called method like this:

var x = 1;
var a = 2;
var b = 3;
Do(o => o.Save(x         


        
5条回答
  •  独厮守ぢ
    2020-12-10 16:27

    Well, you'd need to drill into the expression, find the MethodCallExpression, and then look at the arguments to it. Note that we don't have the value of o, so we've got to assume that the arguments to the method don't rely on that. Also we're still assuming that the lambda expression just relies on it being a MethodCallExpression?

    EDIT: Okay, here's an edited version which evaluates the arguments. However, it assumes you're not really using the lambda expression parameter within the arguments (which is what the new object[1] is about - it's providing a null parameter, effectively).

    using System;
    using System.Linq.Expressions;
    
    class Foo
    {
        public void Save(int x, string y, int z, double d)
        {
        }
    }
    
    class Program
    {
        static void Main()
        {
            var x = 1;
            var a = 2;
            var b = 3;
            ShowValues(o => o.Save(x, "Jimmy", a + b + 5, Math.Sqrt(81)));
        }
    
        static void ShowValues(Expression> expression)
        {
            var call = expression.Body as MethodCallExpression;
            if (call == null)
            {
                throw new ArgumentException("Not a method call");
            }
            foreach (Expression argument in call.Arguments)
            {
                LambdaExpression lambda = Expression.Lambda(argument, 
                                                            expression.Parameters);
                Delegate d = lambda.Compile();
                object value = d.DynamicInvoke(new object[1]);
                Console.WriteLine("Got value: {0}", value);
            }
        }
    }
    

提交回复
热议问题