动态构建具有未知类型的LINQ表达式

时间:2010-12-30 21:51:40

标签: c# linq expression-trees

我想知道是否可以使用此表达式构建器类动态生成lambda表达式,其中在编译时不知道要过滤的类型。

我有一个构造表达式的方法

public static Expression<Func<T, bool>> GetExpression<T>(IList<QueryFilter> filters)

一个QueryFilter对象,

public class QueryFilter 
{
    public string PropertyName { get; set; }       
    public ExpressionType OpType { get; set; } 
    public object Value { get; set; }
}

您可以使用传入的QueryFilters生成一个过滤对象T的新表达式。我想开发一种类型未知的方法,即

public static Expression<Func<T,bool>> GetExpression(IList<QueryFilter> filters, Type type)

所以我可以将类型作为参数传递给System.Reflection,而不必在代码中指定它。例如,沿着这些方向的东西,

    public static Expression NewExpression(IList<QueryFilter> filters, Type T)
    {
        return GetExpression<Type>(filters); 
    }

如果可以使用这种语法,Type替换泛型'T'?因为我认为我不能在&lt;中指定运行时动态类型。 &GT;括号,是否有另一种方式,也许使用

Func<object,bool> 

代替?

2 个答案:

答案 0 :(得分:0)

尝试使用DynamicExpression.ParseLambda

答案 1 :(得分:0)