我刚刚了解到yield return
,它看起来非常不错。我在一个方法中使用它,就像这样:
public IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
if (Name == "Arbitary")
yield return new ValidationResult("Bad Name.", new[] { "Name" });
else if (Email == "BadEmail")
yield return new ValidationResult("Bad Email.", new [] {"Email" });
// further rules follow.
}
然而,我需要修改这个方法,让它从子方法中返回一些验证结果。如果不使用yield
,代码看起来会像这样:
public override IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
// TryValidateObject fills the ICollection you pass it.
List<ValidationResult> retVal = new List<ValidationResult>();
Validator.TryValidateObject(this, vc, retVal, true);
if (Name == "Arbitary")
retVal.Add(new ValidationResult("Bad Name.", new[] { "Name" }));
else if (Email == "BadEmail")
retVal.Add(new ValidationResult("Bad Email.", new[] { "Email" }));
return retVal;
}
是否可以使用yield
重写这个代码?