我正在使用 Delphi 2007,想知道是否 以下是可能的,如果不是的话 可能在另一个版本的 Delphi 中。
我现在的代码看起来像 doo1
但什么
我想要像 doo3
这样的东西。
我已经制作了 doo2
并且它可以工作,但我更喜欢
将 exitIfFalse
函数放在一处
而不是在很多地方作为子过程。
function foo(const bar: Word): boolean;
begin
Result:= bar = 42;
end;
function doo1: integer;
begin
if not foo(42) then begin
Result:= 1;
exit;
end;
if not foo(8) then begin
Result:= 2;
exit;
end;
Result:= 0;
end;
function doo2: integer;
Procedure exitIfFalse(const AResult: boolean; const AResultCode: integer);
begin
if not AResult then begin
Result:= AResultCode;
Abort;
end;
end;
begin
Result:= -1;
try
exitIfFalse(foo(42), 1);
exitIfFalse(foo(8), 2);
Result:= 0;
except
on e: EAbort do begin
end;
end;
end;
function doo3: integer;
begin
exitIfFalse(foo(42), 1);
exitIfFalse(foo(8), 2);
Result:= 0;
end;
最佳答案
Delphi 的更高版本(2009 及更新版本)非常接近:它们允许您编写
function doo3: integer;
begin
if not foo(42) then Exit(1);
if not foo(8) then Exit(2);
Result:= 0;
end;
请注意新的 Exit(value)
形式如何与更传统的 Result
相结合。
Delphi 2007 不正式支持此功能或类似功能。
完全不受支持的黑客可能适合您:Andreas Hausladen 的 DLangExtensions (确保使用较旧的版本)也为 Delphi 2007 提供了此语法。
关于delphi - 是否可以在 Delphi 2007 中创建退出函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26755092/