Acabo de enterarme de yield return
, me parece realmente agradable. Yo lo uso en un método como este:yield return al agregar valores al final de un IEnumerable existente
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.
}
Sin embargo, tengo que cambiar este método para devolver algunas ValidationResults de un método de niño. Sin utilizar yield
, el código se vería así:
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;
}
¿Es posible volver a escribir esto utilizando yield
?
Tenga en cuenta que no haya escrito correctamente "arbitraria". –
@EricLippert Hah, de hecho. Deletreo esto mal todo el tiempo. En este caso, solo es una regla de validación de ejemplo ya que todavía no he resuelto los 'reales'. – Oliver