我刚发现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.
}
但是,我需要更改此方法以从子方法返回一些 ValidationResults。如果不使用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
?