跳转到最终而不退出函数/过程

时间:2013-09-03 22:31:42

标签: delphi

我有以下情况:

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;

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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会执行额外的时间。)