DELPHI:如何使用“break” 在循环或案例之外?
考虑以下 delphi pascal 代码:
var
tc: TComponent
begin
{ do something to get tc }
repeat
if(tc is TDBEdit)then begin
if(check_something_about_edit(tc))then break;
do_something_else_edit(tc);
break;
end else if(tc is TBMemo) then begin
if(check_something_about_memo(tc))then break;
do_something_else_memo(tc);
break;
end;
raise exception.create('invalid component type');
until(true); {single iteration look required to use break }
我知道我可能可以使用 TComponent 做一些多态的事情,但这不是我的问题。 我想知道是否有办法摆脱单次迭代重复直到语句。 如果没有它,我就无法在处理块中的任何位置使用break语句,并且我需要它随时停止处理。
consider the following delphi pascal code:
var
tc: TComponent
begin
{ do something to get tc }
repeat
if(tc is TDBEdit)then begin
if(check_something_about_edit(tc))then break;
do_something_else_edit(tc);
break;
end else if(tc is TBMemo) then begin
if(check_something_about_memo(tc))then break;
do_something_else_memo(tc);
break;
end;
raise exception.create('invalid component type');
until(true); {single iteration look required to use break }
I know there's probably some polymorphic stuff that I could do with TComponent, but that's not my question. I'm wondering if there's a way to get rid of the single iteration repeat-until statement. Without it, I can't use the break statement anywhere in the processing block, and I need that to stop processing at any time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
打包成一个函数,用exit跳回来。 如果重复语句后面有更多代码,请使用本地函数/过程,例如:
Pack it into a function and use exit to jump back. if there is more code to follow the repeat statement, use a local function/procedure, something like:
你实际上正在做的是使用break作为goto。 拉尔夫关于使用函数作为作用域的建议是一个很好的建议。 但除此之外,你不妨诚实地使用“goto finish”。 失去重复将使它实际上更具可读性。
What you are actually doing is using break as a goto. Ralph's suggestion to use a function as a scope is a good one. But otherwise you might as well be honest and use a 'goto finished'. Losing the repeat will make it actually more readable.
还有另一种简单的方法:
There is another easy way to go:
为什么要使用break而不是Exit? Delphi 中的 Break 与大括号语言中的“break”不同。
关于布局的一点。 如果你没有尝试减少太多的空白,它可能不会
正如您在之前的评论中所说,“再花一个小时来确保我所有的 if-else 都正确排列”。
如果您想在此之后执行代码,请使用 Ralph 建议的本地过程,或者包装在 try..finally 中 - finally 中的代码仍将被执行。
Why do you want to use break rather than Exit? Break in Delphi is not the same as "break" in the curly brace languages.
A point about layout. If you didn't try to reduce whitespace so much it mightn't
take "another hour to make sure all my if-else's lined up correctly" as you said in an earlier comment.
If you have code that you want to execute after this, either use Ralph's suggestion of a local procedure, or wrap in a try..finally - the code in the finally will still be executed.