c# - 将值附加到现有 IEnumerable 的末尾时产生返回

标签 c# yield-return

我刚知道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 重写它?

最佳答案

你在找这个吗?

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);
    foreach (var item in retVal)
        yield return item;
    if (Name == "Arbitary")
        yield return new ValidationResult("Bad Name.", new[] { "Name" });
    else if (Email == "BadEmail")
        yield return new ValidationResult("Bad Email.", new[] { "Email" });       
}

如果是这样,我相信第一个版本看起来更好。

关于c# - 将值附加到现有 IEnumerable 的末尾时产生返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10105279/

相关文章:

c# - WPF 每个 TabItem 的初始焦点

c# - 线程内的对象处置

c# - 流式传输 IEnumerable

C#惰性执行+内存理解

c# - 使用 net.msmq 绑定(bind)在 IIS 中托管的 WCF 服务会产生问题

c# - 想要启用可空引用类型时如何处理可选参数?

c# - "yield return"更紧凑的方式?

c# - yield return with try catch,我该如何解决

c# - 是否可以在启动时显示 DisplayAlert (Xamarin.Forms)