2009-10-12 74 views
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()); 
} 

的問題是,我想將更多的信息到錯誤消息。從表達式中獲取信息很容易。但是我怎樣才能達到謂詞的「用戶友好」字符串表示呢?

回答

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