1

.FirstOrDefault()有没有办法通过以下设置摆脱它。我喜欢使用 yield 语句,但我想将 IsRequired 方法压缩到我不必使用.FirstOrDefault().

播放器验证器

protected override IEnumerable<ValidationResult> Validate(PlayerModel entity, IValidationProvider validationProvider)
        {
            yield return ValidationResultHelper.IsRequired(entity.Profile.FirstName, "First Name").FirstOrDefault();

            if (string.IsNullOrWhiteSpace(entity.Profile.LastName))
                yield return new Required("Last Name");
        }

验证器助手

public IEnumerable<ValidationResult> IsRequired(string text, string name)
{
    if (string.IsNullOrWhiteSpace(text))
        yield return new Required(name);
}
4

2 回答 2

2

foreachnull将是另一种选择(在您的示例中没有验证错误的情况下,它不会错误地返回):

protected override IEnumerable<ValidationResult> Validate(PlayerModel entity, IValidationProvider validationProvider)
{
    foreach (var result in ValidationResultHelper.IsRequired(entity.Profile.FirstName, "First Name"))
        yield return result;
    if (string.IsNullOrWhiteSpace(entity.Profile.LastName))
        yield return new Required("Last Name");
}
于 2012-01-11T01:56:44.103 回答
1

我并不熟悉yield return,但在这种情况下,我认为您使用的方式yield returnIsRequired使用错误的工具来完成这项工作。我的结构会略有不同:

ValidatorHelper

// Note this function is almost unnecessary and might be better
// implemented in AddIfRequired if validation is this trivial.
public static bool IsRequired(string text)
{
    return string.IsNullOrWhiteSpace(text);
}

PlayerValidator

private static void AddIfRequired(string text, string name, List<ValidationResult> validationResults)
{
    if (ValidatorHelper.IsRequired(text))
        requiredList.Add(new Required(name));
}

protected override IEnumerable<ValidationResult> Validate(PlayerModel entity, IValidationProvider validationProvider)
{
    List<ValidationResult> validationResults = new List<ValidationResult>();

    AddIfRequired(entity.Profile.FirstName, "First Name", validationResults);
    AddIfRequired(entity.Profile.LastName, "Last Name", validationResults);
    // ...

    return validationResults;
}

如果您真的想使用yield return并保存自己创建一个列表并每次验证所有字段(尽管我不认为这会是一个性能问题),您可以AddIfRequired进入ValidationResultIfRequiredValidate进入:

ValidationResult validationResult;

// ...

validationResult = ValidationResultIfRequired(entity.Profile.FirstName, "First Name");
if (validationResult != null)
    yield return validationResult;

validationResult = ValidationResultIfRequired(entity.Profile.LastName, "Last Name");
// etc
于 2012-01-11T02:02:26.413 回答