循环最佳实践
我有一个非常大的循环,循环 1000 行。 如果找到幻值 1,我将退出循环。 如果未找到幻值 1 但找到幻值 2,则循环需要跳到开头。 现在我正在使用 switch、一些 if 和 goto。 我读到 goto 不是最好的方法。 有没有更好的方法来完成这项工作?
I have a very large loop that loops a 1000 rows. I exit the loop if magic value 1 is found. If magic value 1 is not found but magic value 2 is found then the loop needs to skip to the beginning. Right now I am using a switch, some ifs and a goto. I have read that goto is not the best way. Is there a better way to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
要退出循环,您可以使用 break 语句,要转到下一条记录,您可以使用继续声明。
我不赞成使用 GOTO 语句,我只是指出一个可能的用例
您可以使用 goto 跳转语句来启动/退出循环,但我会保留除非您使用嵌套循环,否则请远离此选项。 我认为 goto 语句仍然有其优化、干净退出等用途。但总的来说,最好相当谨慎使用它。
To exit a loop you can use the break statement, to go onto the next record you can use the continue statement.
I AM NOT CONDONING THE USE OF THE GOTO STATEMENT I AM SIMPLY POINTING OUT A POSSIBLE USE CASE
You can use goto jump statement to start/exit a loop, however I would stay away from this option unless you are using nested looping. I think the goto statement still has its uses for optimizing, exiting cleanly ect.. but in general it is best to use it quite sparingly.
怎么样:
如果“跳到开头”的意思是“跳过此记录并处理下一条记录”,请将
i = 0
替换为继续
。How about this:
If by "skip to the beginning" you mean "skip this record and process the next one," replace
i = 0
withcontinue
.没有
break
的while
变体:A
while
variation with nobreak
:我还不能发表评论(距离 1 个代表点),
但这不是更好吗:
而且我不确定“重新开始搜索”是什么意思。
I can't comment yet ( 1 rep point away)
but wouldn't this be better:
and I'm not sure by whats meant by "restart the search".
我采用#2 情况意味着您不想执行(即跳过)#2 情况中的循环体,而不是您想要将循环重置为 0。(如果我知道,请参阅代码注释向后。)
这个建议可能会引起争议,因为 for 循环中不太传统的条件可以说是自记录规模较低,但如果这不打扰你,一种简洁的方式来写我认为你的想要的是:
I'm taking #2 case to mean that you want to not perform (i.e. skip) the loop body in the #2 case and not that you want to reset the loop to 0. (See the code comments if I've got that backward.)
This suggestion may be controversial because of the less conventional condition in the for loop could be said to be low on the self-documenting scale, but if that doesn't bother you, a concise way of writing what I think you you want is:
请注意,如果您在 MagicValue 为 2 时将计数器设置回 0,并且您的代码从不更改这些值,则您可能会陷入无限循环。
Just note that if you set the counter back to 0 if MagicValue is 2, and your code never changes the values, you are probably going to be in an infinite loop.
更复杂的可能是:
我们定义 2 个扩展方法。
现在您可以这样做:
希望这会有所帮助!
A more complex could be:
We define 2 Extension Methods.
Now you can do this:
hope this helps!