Delphi:在这种情况下 Goto 不被认为是有害的吗?
好的,现在您有了一个 TObjectList 实例。您想要循环遍历其中的项目并从列表中删除一些对象。你不能这样做:
for I := 0 to ObjectList.Count - 1 do
if TMyClass(ObjectList[I]).ShouldRemove then
ObjectList.Delete(I);
...因为一旦你删除了第一个对象,索引计数器我就会错了,循环将不再起作用。
这是我的解决方案:
Again:
for I := 0 to ObjectList.Count - 1 do
if TMyClass(ObjectList[I]).ShouldRemove then
begin
ObjectList.Delete(I);
goto Again;
end;
这是迄今为止我找到的最佳解决方案。如果有人有更简洁的解决方案,我很乐意看到它。
Alright, so you have a TObjectList instance. You want to loop through the items in it and delete some of the objects from the list. You can't do this:
for I := 0 to ObjectList.Count - 1 do
if TMyClass(ObjectList[I]).ShouldRemove then
ObjectList.Delete(I);
...because once you delete the first object the index counter I will be all wrong and the loop won't work any more.
So here is my solution:
Again:
for I := 0 to ObjectList.Count - 1 do
if TMyClass(ObjectList[I]).ShouldRemove then
begin
ObjectList.Delete(I);
goto Again;
end;
This is the best solution I've found to this so far. If anyone has a neater solution I'd love to see it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
这看起来像是 goto 的一个特别糟糕的用法,像这样跳出 for 循环。我认为它有效(因为你正在使用它),但它会让我感到不安。
Try this instead:
That looks like a particularly bad use of goto, jumping out of the for loop like that. I assume it works (since you're using it), but it would give me the willies.
您还可以使用
You can also use
我见过的唯一有效 Goto 用法是 Delphi 帮助中提供的。
尽管在该示例中可以通过将循环移动到本地函数中并使用 EXIT 来避免 Goto。如果子函数不可接受,您仍然可以这样做:
这只是稍微不太理想。
我还没有看到任何其他情况下 Goto 是最好的解决方案。(或者任何好的解决方案)。
Goto 本身并不坏。它是一个流程控制命令,就像 EXIT、BREAK 或 CONTINUE 一样。除了那些其他的仅限于特定情况并由编译器正确管理。 (话虽如此,我采访过的一些程序员认为这些与 Goto 一样有害,我不同意这种观点)Goto 不受限制,你可以用它做的事情可能会产生非常负面的影响。不管怎样,我认为我已经有点超出了问题的范围。 ^_^
The only valid use of Goto I've seen is the one supplied in Delphi's help.
Though Goto could be avoided in that exemple by moving the loop in a local function and using EXIT, for exemple. If a subfunction is not acceptable, you can still do that:
This is just sligthly less optimal.
I have yet to see a single other situation where a Goto would be the best solution.(Or any good at all).
Goto in itself is NOT bad. It's a flow control command just like EXIT, BREAK or CONTINUE. Except that those other are restricted to specific situations and are managed by the compiler correctly. (With that being said, some programmer I spoke with consider those as being as harmful as Goto, a view I don't share) Goto being unrestricted, the things you can do with it can have very negative impacts. Anyway, I think I went a bit beyond the scope of the question already. ^_^