.net 如何返回多个ValidationResults

gj3fmq9x  于 2022-12-27  发布在  .NET
关注(0)|答案(1)|浏览(114)

我正在实现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,而不是多个。有没有更好的方法来处理这个问题?

31moq8wy

31moq8wy1#

您可以尝试删除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;
        }

相关问题