如何获得谓词的主体?

时间:2009-10-12 18:47:56

标签: c# .net lambda predicate

我有一个非常简单的问题,我无法弄明白。

方法代码很简单:

protected void Require<TValidator, TParam>(TValidator validator, Expression<Func<TValidator, TParam>> property, Predicate<TParam> predicate)
{
    var propertyValue = property.Compile().Invoke(validator);
    if(!predicate.Invoke(propertyValue))
        throw new ValidatorInitializationException("Error while initializing validator", GetType());
}

问题是我想将更多信息打包到错误消息中。从表达式中获取信息很容易。但是,如何才能获得谓词的“用户友好”字符串表示形式?

1 个答案:

答案 0 :(得分:2)

你也必须接受它作为表达式树:

protected void Require<TValidator, TParam>(
    TValidator validator, 
    Expression<Func<TValidator, TParam>> property, 
    Expression<Predicate<TParam>> predicateExpression)
{
    var propertyValue = property.Compile().Invoke(validator);
    Predicat<TParam> predicate = predicateExpression.Compile();        
    if(!predicate.Invoke(propertyValue))
    {    
        throw new ValidatorInitializationException(
            "Error while initializing validator: " + predicateExpression,
            GetType());
    }
}