如何跳出内循环回到外循环?
我有 4 个实体“
ObjectA、ObjectB、ObjectC、ObjectD
foreach(ObjectA objectA in listObjectA)
if (relationAB)
foreach(ObjectB objectB in listObjectB)
if (relationBC)
foreach(ObjectC objectC in listObjectC)
if (relationCD)
foreach(ObjectD objectD in listObjectD)
if (I found what I'm looking for)
Do something
因此,当我找到我要查找的内容时,我想转到第一行,第一个 for,但转到列表中的第二个元素。我怎样才能 PS 你能
稍后编辑:这个问题是针对 C# 的。
想出一个更好的方法来完成我想做的事情,而不使用 4 个 for 吗?
I have 4 entities"
ObjectA, ObjectB, ObjectC, ObjectD
foreach(ObjectA objectA in listObjectA)
if (relationAB)
foreach(ObjectB objectB in listObjectB)
if (relationBC)
foreach(ObjectC objectC in listObjectC)
if (relationCD)
foreach(ObjectD objectD in listObjectD)
if (I found what I'm looking for)
Do something
So, when I will found what I wass looking for, I want to go to the first line, to the first for, but to the second element from the list. How can I do this? Whit goto?
Later Edit: This question is for C#.
P.S. Could you think a better way to do what I'm trying to do, whithout using 4 fors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,因为这只是一个“编程语言”问题,所以一般答案是使用您的语言的工具来命名循环,然后在“break”语句上放置正确的名称。
遗憾的是,我认为当前版本的 C 和 C++ 不支持这样的事情,因此在使用它们时您确实必须求助于
goto
。避免这种情况的一个好方法是将您想要中断的循环放入其自己的子例程中,并在完成时执行return
而不是break
。这就是我在使用那些蹩脚语言工作时通常所做的事情。您修改后的示例将是:
注意:标记已从“编程语言”更改为“C#”。对于这个问题来说,这是正确的做法,但很多人喜欢这个答案,所以我不会对其进行重大修改。
Well, since this is just a "programming languages" question, the general answer would be to use your language's facility for naming loops, and then put the proper name on the "break" statement.
Sadly, I don't think the current versions of C and C++ support such a thing, so you would indeed have to resort to a
goto
when using them. A good way to avoid that would be to put the loop you want to break out of into its own subroutine, and just do areturn
when you are done instead of abreak
. That's what I generally do when working in those poor languages.Your revised example would be:
Note: The tag was changed from "programming languages" to "C#". That was the right thing to do for the question, but a lot of people liked this answer so I'm not making major mods to it.
根据语言的不同,您通常可以添加中断标签。不过,我会避免这种情况,并提出以下建议:
阅读具有中断标签和 goto 的代码可能会很困难。将其分解为函数可以使其更易于阅读并且(可能)更易于编写和调试。
Depending on the language, you can generally add break labels. I'd avoid this, however, and suggest the following:
It can be hard to read code that has break labels and gotos. Breaking it into functions can make it easier to read and (probably) easier to write and debug.
最简单的选择是将其全部放入函数中,并使用 return 语句而不是break 语句。
The simplest option is to put it all in a function and use the
return
statement instead of thebreak
statement.在这种情况下最好使用
return
。只需将一些内部
for
放入一个方法中,并在必要时从该方法返回即可。 的链更具可读性。它比循环内部
Better to use
return
in such cases.Just put some of your inner
for
in a method and return from it when necessary. It will be much more readable then a chain ofinside your loops.