从Linq表达式获取参数值 [英] Get the parameter value from a Linq Expression

查看:55
本文介绍了从Linq表达式获取参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

public class MyClass
{
    public bool Delete(Product product)
    {
        // some code.
    }
}

现在我有一个看起来像这样的帮助器类

Now I have a helper class that looks like this

public class Helper<T, TResult>
{

    public Type Type;
    public string Method;
    public Type[] ArgTypes;
    public object[] ArgValues;

    public Helper(Expression<Func<T, TResult>> expression)
    {
        var body = (System.Linq.Expressions.MethodCallExpression)expression.Body;

        this.Type = typeof(T);
        this.Method = body.Method.Name;
        this.ArgTypes = body.Arguments.Select(x => x.Type).ToArray();
        this.ArgValues = ???
    }
}

想法家可以在某个地方使用此代码:

The idea ist to use this code from somewhere:

// I am returning a helper somewhere
public Helper<T> GetMethod<T>()
{
    var product = GetProduct(1);
    return new Helper<MyClass>(x => x.Delete(product));
}

// some other class decides, when to execute the helper 
// Invoker already exists and is responsible for executing the method
// that is the main reason I don't just comile and execute my Expression
public bool ExecuteMethod<T>(Helper<T> helper)
{
    var instance = new MyClass();
    var Invoker = new Invoker(helper.Type, helper.Method, helper.ArgTypes, helper.ArgValues);
    return (bool)Invoker.Invoke(instance);
}

我遇到的问题是如何从表达式本身中提取参数.

The point where I am stuck is how to extract the arguments from the expression itself.

我是这样找到的

((ConstantExpression)((MemberExpression)body.Arguments[0]).Expression).Value

这似乎是带有产品"字段的对象类型,但我相信必须有一个更简单的解决方案.

which seems to be an object type with a field "product" but I believe there must be a simpler solution.

任何建议.

更新

请澄清一下,我根据想要达到的目的修改了我的代码.在我的真实单词应用程序中,我已经有一个可以执行相同操作但没有表达式树的类:

Just to clarify, I modified my code according to what I want to achive. In my real word application I already have a class that does the same but without an expression tree:

var helper = new Helper(typeof(MyClass), "Delete", 
    new Type[] { typeof(Product) }, new object[] {product}));

Helper<T>的主要原因是要在编译时检查方法签名是否有效.

The main reason for my Helper<T> is to have Compile-Time checking if the method signature is valid.

更新2

这是我目前的实现方式,有没有一种更好的方法可以在不使用反射的情况下访问值?

This is my current implementation, is there a better way to acces the values, without using reflection?

public Helper(Expression<Func<T, TResult>> expression)
{
    var body = (System.Linq.Expressions.MethodCallExpression)expression.Body;

    this.Type = typeof(T);
    this.Method = body.Method.Name;
    this.ArgTypes = body.Arguments.Select(x => x.Type).ToArray();

    var values = new List<object>();
    foreach(var arg in body.Arguments)
    {
        values.Add(
            (((ConstantExpression)exp.Expression).Value).GetType()
                .GetField(exp.Member.Name)
                .GetValue(((ConstantExpression)exp.Expression).Value);
        );
    }
    this.ArgValues = values.ToArray();
}

推荐答案

此方法效果很好.它返回表达式的参数类型和值>

This method works pretty well. It returns the argument types and values for an Expression>

    private static KeyValuePair<Type, object>[] ResolveArgs<T>(Expression<Func<T, object>> expression)
    {
        var body = (System.Linq.Expressions.MethodCallExpression)expression.Body;
        var values = new List<KeyValuePair<Type, object>>();

        foreach (var argument in body.Arguments)
        {
            var exp = ResolveMemberExpression(argument);
            var type = argument.Type;

            var value = GetValue(exp);

            values.Add(new KeyValuePair<Type, object>(type, value));
        }

        return values.ToArray();
    }

    public static MemberExpression ResolveMemberExpression(Expression expression)
    {

        if (expression is MemberExpression)
        {
            return (MemberExpression)expression;
        }
        else if (expression is UnaryExpression)
        {
            // if casting is involved, Expression is not x => x.FieldName but x => Convert(x.Fieldname)
            return (MemberExpression)((UnaryExpression)expression).Operand;
        }
        else
        {
            throw new NotSupportedException(expression.ToString());
        }
    }

    private static object GetValue(MemberExpression exp)
    {
        // expression is ConstantExpression or FieldExpression
        if (exp.Expression is ConstantExpression)
        {
            return (((ConstantExpression)exp.Expression).Value)
                    .GetType()
                    .GetField(exp.Member.Name)
                    .GetValue(((ConstantExpression)exp.Expression).Value);    
        }
        else if (exp.Expression is MemberExpression)
        {
            return GetValue((MemberExpression)exp.Expression);
        }
        else
        {
            throw new NotImplementedException();
        }
    }

这篇关于从Linq表达式获取参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆