我正在实现IValidatableObject。在我的Validate函数中,我希望返回多个ValidationResults。如何实现这一点最好?
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> validationResults = new List<ValidationResult>();
if (QuantityTraded < 1 || QuantityTraded > MaxTradeQuantity )
{
validationResults.Add(new ValidationResult($"There must be a quantity greater than zero and less than {MaxTradeQuantity}"));
}
if (TotalAmount > TotalPortfolioCash)
{
validationResults.Add(new ValidationResult($"There is currently not enough money in the Portfolio ({TotalPortfolioCash}) for this order."));
}
if(validationResults.Any() && validationResults.Count > 0)
{
return validationResults;
}
}
这似乎不是一个好方法,因为如果没有ValidationResults,它就不应该返回任何东西。如果我回到使用yield,
yield return new ValidationResult($"There is currently not enough money in the Portfolio ({TotalPortfolioCash}) for this order.");
我一次只能返回一个ValidationResult,而不是多个。有没有更好的方法来处理这个问题?
1条答案
按热度按时间31moq8wy1#
您可以尝试删除
if(validationResults.Any() && validationResults.Count > 0)
,无论您是否向validationResults
添加了数据,都应该在Validate '方法中返回IEnumerable<ValidationResult>
: