返回一个元素,从迭代器块 - 迭代器不能包含return语句 [英] Returning a single element from an iterator block - Iterator cannot contain return statement
本文介绍了返回一个元素,从迭代器块 - 迭代器不能包含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;
}
这篇关于返回一个元素,从迭代器块 - 迭代器不能包含return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文