当前位置 : 主页 > 编程语言 > delphi >

DELPHI:如何在循环或案例之外使用“break”?

来源:互联网 收集:自由互联 发布时间:2021-06-23
考虑以下delphi pascal代码: var tc: TComponentbegin{ 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(
考虑以下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做一些多态的东西,但这不是我的问题.我想知道是否有办法摆脱单次迭代repeat-until语句.没有它,我不能在处理块的任何地方使用break语句,我需要随时停止处理.

将其打包到一个函数中并使用exit跳回.如果有更多代码要遵循repeat语句,请使用本地函数/过程,例如:

procedure ...
  procedure testsomething(tc: TComponent);
  begin 
    if(tc is TDBEdit)then begin
      if(check_something_about_edit(tc))then exit;
      do_something_else_edit(tc);
      exit;
    end else if(tc is TBMemo) then begin
      if(check_something_about_memo(tc))then exit;
      do_something_else_memo(tc);
      exit;
    end;
    raise exception.create('invalid component type');
  end;

var
  tc: TComponent;
begin
{ do something to get tc }
  try
    TestSomething(tc);
    { do something more }
  except
     ...
  end;
end;
网友评论