如何将表达式编译为实际结果?

时间:2011-08-09 18:15:56

标签: c# c#-4.0 expression-trees

我正在使用表达式围绕Web服务调用构建API,以允许开发人员指定查询并让ExpressionVisitor将Expression转换为查询字符串。请求是XML,其中包含一个包含查询字符串的特定元素。

例如,我可以做类似这样的事情,它将检索银行名称为Bank 1或Bank 2的所有支票账户:

“bankname ='Bank 1'或bankname ='Bank 2'”

Web服务可以处理更复杂的查询,但我现在只是坚持这一点。

所以我有一个CheckingAccount类:


[IntacctObject("checkingaccount")]
public class CheckingAccount : Entity
{
    [IntacctElement("bankaccountid")]
    public string Id { get; set; }

    [IntacctElement("bankname")]
    public string BankName { get; set; }
}

ExpressionVisitor,其主要功能是转换如下表达式:

Expression> expression = ca => ca.BankName == "Bank 1" || ca.BankName == "Bank 2"

进入查询:“bankname ='Bank 1'或bankname ='Bank 2'”

这不是那么难。当我引入局部变量时,事情开始崩溃的地方:


var account = new CheckingAccount { BankName = "Bank 1" };
string bankName = "Bank 2";

Expression> expression = ca => ca.BankName == account.BankName || ca.BankName == bankName;

我知道如何处理一个简单的局部变量(即字符串bankName =“Bank 2”)但处理另一种类型(var account = new CheckingAccount {BankName =“Bank 1”})要复杂得多

在一天结束时,这些是我需要弄清楚如何处理的重大问题。我知道有更复杂的情况,但我现在并不那么关心。

这是我的表达式访问者(请注意方法CreateFilter的通用约束):


internal class IntacctWebService30ExpressionVisitor : ExpressionVisitor
{
    private readonly List _Filters = new List();
    private IntacctWebServicev30SimpleQueryFilter _CurrentSimpleFilter;
    private IntacctWebServicev30ComplexQueryFilter _CurrentComplexFilter;
    private MemberExpression _CurrentMemberExpression;

    public string CreateFilter(Expression> expression) where TEntity : Entity
    {

        Visit(expression);

        string filter = string.Join(string.Empty, _Filters.Select(f => f.ToString()).ToArray());
        return filter;
    }

    protected override Expression VisitBinary(BinaryExpression node)
    {
        switch (node.NodeType)
        {
            case ExpressionType.AndAlso:
            case ExpressionType.OrElse:
                _CurrentComplexFilter = new IntacctWebServicev30ComplexQueryFilter { ExpressionType = node.NodeType };
                break;
            case ExpressionType.Equal:
            case ExpressionType.GreaterThan:
            case ExpressionType.GreaterThanOrEqual:
            case ExpressionType.LessThan:
            case ExpressionType.LessThanOrEqual:
            case ExpressionType.NotEqual:
                _CurrentSimpleFilter = new IntacctWebServicev30SimpleQueryFilter { ExpressionType = node.NodeType };
                break;
        }

        return base.VisitBinary(node);
    }

    protected override Expression VisitMember(MemberExpression node)
    {
        var attr = node.Member.GetAttribute();
        if (attr != null)
            _CurrentSimpleFilter.FieldName = attr.FieldName;
        else
            _CurrentMemberExpression = node;

        return base.VisitMember(node);
    }

    protected override Expression VisitConstant(ConstantExpression node)
    {
        object value = Expression.Lambda>(node).Compile().Invoke();

        string fieldValue = extraxtFieldValue(value, node);

        _CurrentSimpleFilter.FieldValue = fieldValue;

        if (_CurrentComplexFilter != null)
        {
            if (_CurrentComplexFilter.Left == null)
            {
                _CurrentComplexFilter.Left = _CurrentSimpleFilter;
            }
            else if (_CurrentComplexFilter.Right == null)
            {
                _CurrentComplexFilter.Right = _CurrentSimpleFilter;
                _Filters.Add(_CurrentComplexFilter);
            }
            else
                throw new InvalidOperationException();
        }
        else
        {
            _Filters.Add(_CurrentSimpleFilter);
        }

        return base.VisitConstant(node);
    }

    private string extraxtFieldValue(object value)
    {
        string fieldValue;
        if (value is DateTime)
            fieldValue = ((DateTime)value).ToString("yyyy-MM-dd");
        else if (value is string)
            fieldValue = value.ToString();
        else if (value.GetType().IsEnum)
        {
            throw new NotImplementedException();
        }
        else
        {
            // Not sure if this is the best way to do this or not but can't figure out how
            // else to get a variable value.

            // If we are here then we are dealing with a property, field, or variable.
            // This means we must extract the value from the object.
            // In order to do this we will rely on _CurrentMemberExpression
            if (_CurrentMemberExpression.Member.MemberType == MemberTypes.Property)
            {
                fieldValue = value.GetType().GetProperty(_CurrentMemberExpression.Member.Name).GetValue(value, null).ToString();
            }
            else if (_CurrentMemberExpression.Member.MemberType == MemberTypes.Field)
            {
                fieldValue = value.GetType().GetFields().First().GetValue(value).ToString();
            }
            else
            {
                throw new InvalidOperationException();
            }
        }

        return fieldValue;
    }
}

如果你想了解更多细节,请告诉我。

由于

2 个答案:

答案 0 :(得分:0)

看看an article about this very issue from Matt Warren。他为一个正是这样做的类提供了源代码,并解释了它是如何做到的。它也包含在his IQToolkit中。

答案 1 :(得分:-1)

如果您对使用开源第三方库感兴趣,可以查看Expression Tree Serialization。我相信它能满足您的需求。