2

我有以下情况:

procedure Test;
begin
 repeat
  TryAgain := FALSE;
  try
   // Code
   // Code
   if this and that then begin
    TryAgain := TRUE;
    exit;
   end;
  finally
   // CleanUpCode
  end;
 until TryAgain = FALSE;
end;

如何在不调用的情况下跳转到 finally 部分,exit以便它也自动调用repeat页脚?

4

2 回答 2

11

用于Continue进行下一次迭代。finally块部分中的代码try..finally设计为始终执行,因此即使您强制跳到下一次迭代:

procedure TForm1.Button1Click(Sender: TObject);
begin
  repeat
    TryAgain := False;
    try
      if SomeCondition then
      begin
        TryAgain := True;
        // this will proceed the finally block and go back to repeat
        Continue;
      end;
      // code which would be here will execute only if SomeCondition
      // is False, because calling Continue will skip it
    finally
      // code in this block is executed always
    end;
  until
    not TryAgain;
end;

但是同样的逻辑你可以简单地这样写:

procedure TForm1.Button1Click(Sender: TObject);
begin
  repeat
    TryAgain := False;
    try
      if SomeCondition then
      begin
        TryAgain := True;
      end
      else
      begin
        // code which would be here will execute only if SomeCondition
        // is False
      end;
    finally
      // code in this block is executed always
    end;
  until
    not TryAgain;
end;
于 2013-09-03T22:54:47.977 回答
7

call你最终不应该这样做。只需删除exit应该允许它在finally每次循环迭代结束时自动运行代码。这是演示的代码:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  i, j, Dummy: Integer;
  TryAgain: Boolean;

begin
  i := 0;
  Dummy := 0;
  TryAgain := True;
  repeat
    try
      for j := 0 to 200 do
        Dummy := Dummy + 1;
    finally
      Inc(i);
    end;
    TryAgain := (i < 10);
  until not TryAgain;
  WriteLn(i);
  ReadLn;
end.

如果finally没有在每次迭代结束时执行,则repeat永远不会结束,因为i只会在 中递增finally,如果没有执行,则永远不会满足终止条件。相反,它退出并输出11,这表明finally每次循环迭代都运行一次repeat。(它输出11而不是10因为finally执行额外的时间。)

于 2013-09-03T22:49:39.947 回答