Result 概要:
-
Result是 Delphi 编译器自动为有返回值的函数创建的局部变量 -
它的类型自动匹配函数的返回类型
-
不需要手动声明,直接使用即可
-
这是 Delphi/Object Pascal 语言的核心特性之一
-
对于记录类型,
Result就是一个完整的记录实例,可以直接访问其字段
下面以一个记录类型为例进行说明
typeTDeptSupplierInfo = recordDeptID: 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; beginResult.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; beginResult := 42; // Result 是 Integer 类型 end;function GetString: string; beginResult := 'Hello'; // Result 是 string 类型 end;// 记录类型 function GetRecord: TDeptSupplierInfo; beginResult.DeptID := 10; // Result 是 TDeptSupplierInfo 类型Result.SupplierID := 20; end;// 类类型 function GetObject: TObject; beginResult := TObject.Create; // Result 是 TObject 类型 end;// 接口类型 function GetInterface: IInterface; beginResult := nil; // Result 是 IInterface 类型 end;// 动态数组 function GetArray: TArray<Integer>; beginSetLength(Result, 3); // Result 是 TArray<Integer> 类型Result[0] := 1; end;
4. 两种赋值方式
对于记录类型,有两种使用方式:
// 方式1:直接给 Result 赋值一个完整记录 function CreateInfo(const ATag: Integer): TDeptSupplierInfo; beginif (ATag mod 10) = 0 thenResult := TDeptSupplierInfo.Create(ATag) // 需要构造函数elseResult := Default(TDeptSupplierInfo); // 使用默认值 end;// 方式2:逐个字段赋值(您使用的方式) function CreateInfo(const ATag: Integer): TDeptSupplierInfo; beginif (ATag mod 10) = 0 thenbeginResult.DeptID := ATag div 10;Result.SupplierID := 0;endelsebeginResult.DeptID := 0;Result.SupplierID := (ATag - 1) div 10;end; end;
5. 新旧语法对比
Delphi 也支持使用函数名作为返回值(旧语法),但 Result 是推荐方式:
// 旧语法(不推荐) function GetValue: Integer; beginGetValue := 42; // 使用函数名 end;// 新语法(推荐) function GetValue: Integer; beginResult := 42; // 使用 Result end;
6. 注意事项
// Result 默认值是不确定的 function GetRecord: TDeptSupplierInfo; begin// 此时 Result.DeptID 和 Result.SupplierID 的值是未定义的(随机值)// 字符串类型会被初始化为空字符串// 接口和动态数组会被初始化为 nil// 但记录类型不会被自动清零! Result.DeptID := 10; // 必须显式赋值Result.SupplierID := 20; end;// 如果希望清零,可以这样: function GetRecord: TDeptSupplierInfo; beginResult := Default(TDeptSupplierInfo); // 清零所有字段Result.DeptID := 10; end;
