Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c# - get end values from lambda expressions method parameters

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<HomeController>(o => o.Save(x, "Jimmy", a+b+5, Math.Sqrt(81)));

public static void Do<T>(Expression<Action<T>> expression) where T : Controller
{
  // get the values 1,Jimmy,10,9 here
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Foo>(o => o.Save(x, "Jimmy", a + b + 5, Math.Sqrt(81)));
    }

    static void ShowValues<T>(Expression<Action<T>> 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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...