Composing invocations with Expression> the same way as Func

前端 未结 1 1909
你的背包
你的背包 2021-01-28 12:07

Consider a class that can be used as a member of multiple other classes:

class Customer {
    public string FirstName {get;set;}
    public string LastName {get;         


        
相关标签:
1条回答
  • 2021-01-28 12:38

    Unfortunately, C# does not currently provide a way to compose expressions from Expression<Func<...>> objects. You have to use expression trees, which is quite a bit longer:

    static Expression<Func<T,bool>> CheckExpr<T>(Expression<Func<T,Customer>> conv, string first, string last) {
        var arg = Expression.Parameter(typeof(T));
        var get = Expression.Invoke(conv, arg);
        return Expression.Lambda<Func<T,bool>>(
            Expression.MakeBinary(
                ExpressionType.AndAlso
            ,   Expression.MakeBinary(
                    ExpressionType.Equal
                ,   Expression.Property(get, nameof(Customer.FirstName))
                ,   Expression.Constant(first)
                )
            ,   Expression.MakeBinary(
                    ExpressionType.Equal
                ,   Expression.Property(get, nameof(Customer.LastName))
                ,   Expression.Constant(last)
                )
            )
        ,   arg
        );
    }
    
    0 讨论(0)
提交回复
热议问题