返回一个元素,从迭代器块 - 迭代器不能包含return语句
问题描述:
让我们说我有下面的方法。在某些来到
Let's say I have the following method. In some came
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);
}
}
}
实际情况实际上是一个有点复杂,但我已经留下了很多出用于说明目的。
The actual situation is actually a bit more complex but I've left a lot out for illustration purposes.
点是在某些情况下,我想迭代器继续收集多个错误......但在其他情况下,有一个致命的错误,我只是想返回一个错误,但它不会让我:
The point is in some cases, I want to iterator to continue collecting multiple errors...but in other cases there is a fatal error and I only want to return a single error but it will not let me:
Iterator cannot contain return statement
我应该怎么办?
What should I do?
答
如果你只是想返回大小为一的集合,你可以这样做:
If you just want to return a collection of size one, you can do this:
if(!user.Activated)
{
yield return new ValidationResult("NotActived", Resources.UserNotActivated);
yield break;
}