是否可以在Delphi 2007中创建退出功能?

时间:2014-11-05 10:38:36

标签: 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;

1 个答案:

答案 0 :(得分:8)

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提供了这种语法。

相关问题