问题描述
基本上我希望得到一个所谓的方法是这样的参数值:
VAR X = 1;
变种一个= 2;
变种B = 3;
DO< HomeController的>(O => o.Save(X,吉米,A + B + 5的Math.sqrt(81)));
公共静态无效走走LT; T>(出pression<作用< T>>除权pression)其中T:控制器
{
//获取值1,吉米,10,9这里
}
那么,你需要钻到EX pression,找到 MethodCallEx pression
,再看看参数吧。需要注意的是我们没有的 0
的价值,所以我们必须假设参数的方法不依赖于这一点。此外,我们还在假设拉姆达EX pression仅仅依赖于它是一个 MethodCallEx pression
?
编辑:好的,这里有一个编辑的版本,它计算参数。但是,假设你的没有的真正使用中的参数拉姆达EX pression参数(这是什么新的对象[1]
约 - 它提供了一个空参数,有效的)
使用系统;
使用System.Linq.Ex pressions;
类Foo
{
公共无效保存(INT X,y字符串,INT Z,双D)
{
}
}
类节目
{
静态无效的主要()
{
变种X = 1;
变种一个= 2;
变种B = 3;
ShowValues<富>(O => o.Save(X,吉米,A + B + 5的Math.sqrt(81)));
}
静态无效ShowValues< T>(出pression<作用< T>>除权pression)
{
VAR通话= EX pression.Body为MethodCallEx pression;
如果(调用== NULL)
{
抛出新的ArgumentException(不是一个方法调用);
}
的foreach(前pression在call.Arguments参数)
{
LambdaEx pression波长=前pression.Lambda(参数,
EX pression.Parameters);
代表D = lambda.Compile();
对象值= d.DynamicInvoke(新对象[1]);
Console.WriteLine(GOT值:{0},值);
}
}
}
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
}
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);
}
}
}
这篇关于从拉姆达EX pressions方法参数得到最终值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!