Delphi 关于函数返回值变量Result
Result 概要:
-
Result是 Delphi 编译器自动为有返回值的函数创建的局部变量 -
它的类型自动匹配函数的返回类型
-
不需要手动声明,直接使用即可
-
这是 Delphi/Object Pascal 语言的核心特性之一
-
对于记录类型,
Result就是一个完整的记录实例,可以直接访问其字段
下面以一个记录类型为例进行说明
type TDeptSupplierInfo = record DeptID: Integer; SupplierID: Integer; // 辅助方法 function isDept: Boolean; // 是否部门 function IsSupplier: Boolean; // 是否供应商 function IsValid: Boolean; // 是否有效 function AsString: string; // 返回 "部门ID,供应商ID" 格式 end;
1. Result 是自动声明的
在 Delphi 中,任何有返回值的函数都会自动拥有一个名为 Result 的局部变量,它的类型就是函数的返回类型。
function GetDeptAndSupplierID(const ATag: Integer): TDeptSupplierInfo; // ↑返回类型 ↑编译器自动声明了 Result: TDeptSupplierInfo begin // 等价于在函数内部自动声明了: // var Result: TDeptSupplierInfo; Result.DeptID := ATag div 10; // 可以直接使用 Result.SupplierID := 0; // 不需要手动声明 end;
2. 编译器层面的等价代码
// 您写的代码: function TfraModuleCPRK.GetDeptAndSupplierID(const ATag: Integer): TDeptSupplierInfo; begin Result.DeptID := ATag div 10; Result.SupplierID := 0; end; // 编译器内部等价于: function TfraModuleCPRK.GetDeptAndSupplierID(const ATag: Integer): TDeptSupplierInfo; var _Result: TDeptSupplierInfo; // 编译器自动添加 begin _Result.DeptID := ATag div 10; _Result.SupplierID := 0; // 函数结束时,自动返回 _Result 的值 end;
3. 适用于所有返回类型
Result 变量适用于任何返回类型:
// 基本类型 function GetInteger: Integer; begin Result := 42; // Result 是 Integer 类型 end; function GetString: string; begin Result := 'Hello'; // Result 是 string 类型 end; // 记录类型 function GetRecord: TDeptSupplierInfo; begin Result.DeptID := 10; // Result 是 TDeptSupplierInfo 类型 Result.SupplierID := 20; end; // 类类型 function GetObject: TObject; begin Result := TObject.Create; // Result 是 TObject 类型 end; // 接口类型 function GetInterface: IInterface; begin Result := nil; // Result 是 IInterface 类型 end; // 动态数组 function GetArray: TArray<Integer>; begin SetLength(Result, 3); // Result 是 TArray<Integer> 类型 Result[0] := 1; end;
4. 两种赋值方式
对于记录类型,有两种使用方式:
// 方式1:直接给 Result 赋值一个完整记录 function CreateInfo(const ATag: Integer): TDeptSupplierInfo; begin if (ATag mod 10) = 0 then Result := TDeptSupplierInfo.Create(ATag) // 需要构造函数 else Result := Default(TDeptSupplierInfo); // 使用默认值 end; // 方式2:逐个字段赋值(您使用的方式) function CreateInfo(const ATag: Integer): TDeptSupplierInfo; begin if (ATag mod 10) = 0 then begin Result.DeptID := ATag div 10; Result.SupplierID := 0; end else begin Result.DeptID := 0; Result.SupplierID := (ATag - 1) div 10; end; end;
5. 新旧语法对比
Delphi 也支持使用函数名作为返回值(旧语法),但 Result 是推荐方式:
// 旧语法(不推荐) function GetValue: Integer; begin GetValue := 42; // 使用函数名 end; // 新语法(推荐) function GetValue: Integer; begin Result := 42; // 使用 Result end;
6. 注意事项
// Result 默认值是不确定的 function GetRecord: TDeptSupplierInfo; begin // 此时 Result.DeptID 和 Result.SupplierID 的值是未定义的(随机值) // 字符串类型会被初始化为空字符串 // 接口和动态数组会被初始化为 nil // 但记录类型不会被自动清零! Result.DeptID := 10; // 必须显式赋值 Result.SupplierID := 20; end; // 如果希望清零,可以这样: function GetRecord: TDeptSupplierInfo; begin Result := Default(TDeptSupplierInfo); // 清零所有字段 Result.DeptID := 10; end;

浙公网安备 33010602011771号