delphi - 是否可以在 Delphi 2007 中创建退出函数?

标签 delphi delphi-2007

我正在使用 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/

相关文章:

delphi - Delphi中一个和多个 "type" block 的区别

delphi - 使用 Rad Studio 2007 读取 vcl.net 应用程序中的代理详细信息

delphi - 如何阅读页面源 TWebBrowser Firemonkey

delphi - 服务处的 LogonUser + CreateProcessAsUser = 错误 1314

delphi - 在环境变量 "Path"的路径中搜索文件

德尔福2007 : IDE Model View: Generate Documentation missing?

delphi - 在非常慢的查询中,如何指示进度百分比

delphi - 在Delphi匿名方法中不能使用var参数吗?

algorithm - 将帧转换为 NTSC 丢帧时间码

delphi - Delphi中的目录路径操作?