簡體   English   中英

替換表達式樹中的參數值

[英]Replace parameter value in Expression Tree

搜索了一段時間之后,我仍然找不到所需的答案。 我找到了有關從樹中添加和刪除參數的答案,但沒有找到有關替換特定參數的答案。

我的第一個方法正在按我的意願工作,我需要用Uri轉義值替換partitionKey值,然后返回未轉義的結果。

public override IList<T> GetRowEntityList(string partitionKey)
{
    IList<T> rowEntities =  base.GetRowEntityList(Uri.EscapeDataString(partitionKey));
    return rowEntities.Select(UnEscapeRowEntity).ToList();
}

我遇到的問題是重寫此方法以使其行為相同。 我已經知道類型T具有屬性PartitionKeyRowKey但也可以具有任何其他數量的屬性。

對於樣本謂詞:

x => x.RowKey == "foo/bar" && x.SomeValue == "test" 

我希望它會成為

x => x.RowKey == Uri.EscapeDataString("foo/bar") && x.SomeValue == "test"  

有沒有辦法做到這一點?

我的基類使用此謂詞通過Where(predicate)調用Where(predicate)包含T類型實體的表上進行表查找

public override IList<T> GetRowEntityList(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
    //modify predicate value here

    return base.GetRowEntityList(predicate);
}

您需要實現一個ExpressionVisitor

class MyVisitor : ExpressionVisitor
{
    protected override Expression VisitBinary(BinaryExpression node)
    {
        if(CheckForMatch(node.Left))
            return Expression.Equal(node.Left, Rewrite(node.Right));

        if(CheckForMatch(node.Right))
            return Expression.Equal(Rewrite(node.Left), node.Right);

        return Expression.MakeBinary(node.NodeType, Visit(node.Left), Visit(node.Right));
    }

    private bool CheckForMatch(Expression e)
    {
        MemberExpression me = e as MemberExpression;
        if(me == null)
            return false;

        if(me.Member.Name == "RowKey" || me.Member.Name == "PartitionKey")
            return true;
        else
            return false;
    }

    private Expression Rewrite(Expression e)
    {
        MethodInfo mi = typeof(Uri).GetMethod("EscapeDataString");

        return Expression.Call(mi, e);
    }
}

我認為是對的。 測試有點困難。 請注意,這僅適用於(x => x.RowKey == "some string")的有限情況。 它不適用於(x => x.RowKey.Equals("somestring") 。它也不適用(x => x.RowKey() == "some string")

然后,您可以使用實現的訪問者來重寫謂詞:

Expression<Func<T, bool>> predicate = (s => s.RowKey == "1 2");

ExpressionVisitor v = new MyVisitor();
Expression<Func<T, bool>> rewrittenPredicate = v.Visit(predicate);

//rewrittenPredicate then tests if s.RowKey == "1%202"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM