delphi - 如何在 Delphi 中以结果记录退出?

Delphi 有一个带值退出的选项(示例:Exit(0);),但是如果返回值是一条记录,我该如何带值退出?

TIntResult = record
  Value: Integer;
  Error: String;
end;

function GetCount: TIntResult;
begin
  if not IsLoggedIn then
    Exit(Value: 0; Error: 'Not logged in'); // I want this

  if not IsAdmin then
    Exit(TIntResult(Value: 0; Error: 'Not Admin')); // or this
  ...
end;

最佳答案

当然,您始终可以使用Result 变量和Exit

但是,如果您想使用 Delphi 2009+ Exit(...) 语法——而不给它一个 TIntResult 类型的变量——,两个最明显的选择是这些:

使用构造函数

type
  TIntResult = record
    Value: Integer;
    Error: string;
    constructor Create(AValue: Integer; const AError: string);
  end;

{ TIntResult }

constructor TIntResult.Create(AValue: Integer; const AError: string);
begin
  Value := AValue;
  Error := AError;
end;

然后你可以这样做:

function Test: TIntResult;
begin
  // ...
  Exit(TIntResult.Create(394, 'Invalid page.'));
end;

使用TIntResult-返回函数

function IntRes(AValue: Integer; const AError: string): TIntResult;
begin
  Result.Value := AValue;
  Result.Error := AError;
end;

然后你可以这样做:

function Test: TIntResult;
begin
  // ...
  Exit(IntRes(394, 'Invalid page.'));
end;

https://stackoverflow.com/questions/69584078/

相关文章:

haskell - 为什么我的 ByteString 在我的 x86_64 架构上是 BigEndi

amazon-web-services - 在哪里可以找到 AWS ARN 中服务和资源类型部分的可

kotlin - 获取列表 kotlin 范围之间的项目

swift - 如何区分 Swift 中的泛型值是什么?

arrays - 为什么我在执行 strcat() 时得到错误的源字符串输出?

haskell - 如何使组合数据构造函数成为类的实例?

python - 为什么在为 python 安装 psutil 包时会出现错误?

javascript - 使用 reduce,从一个对象数组中,在对象的数组属性中创建一组元素

c# - GraphQL : Not Getting EF Related objects afte

c++ - 将 std::string 转换为 std::string_view 的时间复杂度