写收益率的另一种方法
本文关键字:方法 另一种 收益率 | 更新日期: 2023-09-27 18:20:08
有没有办法通过以下设置来消除.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");
}
ValidatorHelper
public IEnumerable<ValidationResult> IsRequired(string text, string name)
{
if (string.IsNullOrWhiteSpace(text))
yield return new Required(name);
}
foreach
将是另一个选项(在没有验证错误的情况下,它不会像您的示例中那样错误地返回null
):
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");
}
我对yield return
并不是很熟悉,但在这种情况下,我认为您在IsRequired
中使用yield return
的方式是使用了错误的工具。我的结构略有不同:
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
转换为ValidationResultIfRequired
,将Validate
转换为:
ValidationResult validationResult;
// ...
validationResult = ValidationResultIfRequired(entity.Profile.FirstName, "First Name");
if (validationResult != null)
yield return validationResult;
validationResult = ValidationResultIfRequired(entity.Profile.LastName, "Last Name");
// etc