我有一个非常简单的问题,我无法弄明白。
方法代码很简单:
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());
}
问题是我想将更多信息打包到错误消息中。从表达式中获取信息很容易。但是,如何才能获得谓词的“用户友好”字符串表示形式?
答案 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());
}
}