如何返回多个ValidationResults



我正在实现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,而不是多个。有更好的办法吗?

您可以尝试删除if(validationResults.Any() && validationResults.Count > 0),无论您是否向validationResults添加数据,您都应该在Validate '方法中返回IEnumerable<ValidationResult>:

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."));
}
return validationResults;
}

相关内容

  • 没有找到相关文章

最新更新