【发布时间】:2012-12-07 08:47:27
【问题描述】:
假设我有以下方法。有的来了
public IEnumerable<ValidationResult> Validate(UserLoginCommand command)
{
User user = userRepository.Get(u => u.Email == command.UserEmail);
if(user != null)
{
if(!user.Activated)
{
return new IEnumerable<ValidationResult>() {new ValidationResult("NotActived", Resources.UserNotActivated)};
}
if(user.IsPasswordIncorrent)
{
yield return new ValidationResult("IncorrectPassword", Resources.IncorrentPassword);
}
}
}
实际情况其实要复杂一些,但为了说明,我省略了很多。
重点是在某些情况下,我希望迭代器继续收集多个错误...但在其他情况下,会出现致命错误,我只想返回一个错误但它不会让我:
Iterator cannot contain return statement
我该怎么办?
【问题讨论】:
-
我认为错误信息非常明确。您不能混合使用
yield和return,因为函数执行会延迟到迭代器被调用。我建议摆脱yield并构建自己的枚举。我希望 Jon Skeet 或 Eric Lippert 能在这里准确地解释为什么编译器无法处理这种情况。
标签: c# .net c#-4.0 iterator yield