模拟 ForEach 函数中的 break 语句
这更多是一个假设的问题,因为我越来越多地使用 .NET 3.5 以及 lambda 表达式和匿名委托。举个简单的例子:
static void Main(string[] args)
{
List<int> numList = new List<int>(int[] { 1, 3, 5, 7, 9, 11, 12, 13, 15 });
numList.ForEach(i =>
{
if (i % 2 == 1)
Console.Write(i);
else
return;
});
Console.ReadLine();
}
这将产生输出:
13579111315
当然,我真正希望它做的是在 12 之后停止执行 ForEach 函数,而不是打印 13 或 15。在传统的 foreach 构造中,您将有一个中断(而不是我的示例中的 return) ,循环就会结束。然而,在这种情况下,休息是非法的。您会收到以下消息:
没有可以中断或继续的封闭循环
是否有一个我可以在这里轻松使用的构造来获得所需的结果,或者如果您不打算实际运行所需的结果,在这种情况下使用标准 foreach 循环是否更好列表中每个成员的代码?
This is more of a hypothetical question as I am using .NET 3.5 more and more along with lambda expressions and anonymous delegates. Take this simple example:
static void Main(string[] args)
{
List<int> numList = new List<int>(int[] { 1, 3, 5, 7, 9, 11, 12, 13, 15 });
numList.ForEach(i =>
{
if (i % 2 == 1)
Console.Write(i);
else
return;
});
Console.ReadLine();
}
This will produce the output:
13579111315
Of course, what I'd really like it to do is to stop executing the ForEach function after 12, and not print 13 or 15. In a traditional foreach construct, you would have a break (instead of the return in my example), and the loop would end. However, a break is illegal in this case. You get the following message:
No enclosing loop out of which to break or continue
Is there a construct I could easily employ here to get the desired result, or is it just better to use a standard foreach loop in this case if you don't intend to actually run the desired code on every single member of a list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用标准的
foreach
循环即可。这几乎总是比使用 lambda 表达式更简单、更不易混淆 - 您不会对捕获的变量等感到困惑。您可能希望阅读 Eric Lippert 对此也发表了帖子。
如果您已获得委托并且您只想在列表中的每个元素上执行它,则
List.ForEach
非常有用 - 但否则我会坚持使用普通语言功能。Just use a standard
foreach
loop. This is almost always simpler and less confusing than using a lambda expression - you don't get confusion over captured variables etc.You may wish to read Eric Lippert's post on this as well.
List<T>.ForEach
is useful if you've been handed a delegate and you just want to execute it on each element in the list - but otherwise I'd stick with the normal language feature.