我有以下情况:
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
页脚?
答案 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
会执行额外的时间。)