如何获取谓词主体?

发布于 2024-08-07 00:49:58 字数 508 浏览 5 评论 0原文

我有一个非常简单的问题,但我无法弄清楚。

方法代码很简单:

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());
}

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

I Have a quite simple question that I just cant figure out.

The method code is simple:

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());
}

The problem is that I would like to pack more info into the error message. Getting information out of the expression is easy. But how can I get to a "user friendly" string representation of the predicate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑叹一世浮沉 2024-08-14 00:49:58

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

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());
    }
}

You'd have to accept that as an expression tree too:

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());
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文