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

Ben*_*iss 2 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;
Run Code Online (Sandbox Code Playgroud)

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

TLa*_*ama 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;
Run Code Online (Sandbox Code Playgroud)

但是你可以用这种方式写出同样的逻辑:

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;
Run Code Online (Sandbox Code Playgroud)


Ken*_*ite 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.
Run Code Online (Sandbox Code Playgroud)

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