我有一个获取规则对象列表并生成List>的函数。 这是我的代码:
public static List<Func<T, bool>> CompileRule<T>(List<Rule> rules)
{
var compiledRules = new List<Func<T, bool>>();
// Loop through the rules and compile them against the properties of the supplied shallow object
rules.ForEach(rule =>
{
var genericType = Expression.Parameter(typeof(T));
var key = Expression.Property(genericType, rule.ComparisonPredicate);
var propertyType = typeof(T).GetProperty(rule.ComparisonPredicate).PropertyType;
var value = Expression.Constant(Convert.ChangeType(rule.ComparisonValue, propertyType));
var binaryExpression = Expression.MakeBinary(rule.ComparisonOperator, key, value);
compiledRules.Add(Expression.Lambda<Func<T, bool>>(binaryExpression, genericType).Compile());
});
// Return the compiled rules to the caller
return compiledRules;
}
我想更改函数以返回在已编译函数和(&amp;&amp;)之间生成的Func,并在Funcs
之间返回Func<T, bool>
。
规则类看起来像这样:
public class Rule
{
///
/// Denotes the rules predictate (e.g. Name); comparison operator(e.g. ExpressionType.GreaterThan); value (e.g. "Cole")
///
public string ComparisonPredicate { get; set; }
public ExpressionType ComparisonOperator { get; set; }
public string ComparisonValue { get; set; }
///
/// The rule method that
///
public Rule(string comparisonPredicate, ExpressionType comparisonOperator, string comparisonValue)
{
ComparisonPredicate = comparisonPredicate;//property name
ComparisonOperator = comparisonOperator;//operation
ComparisonValue = comparisonValue;//target value
}
}