You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi初始化记录数组时遇“Constant Expression Expected”错误求助

Delphi常量记录数组初始化报错:Constant expression expected

问题成因

TArray<String>属于动态数组,是引用类型。Delphi的常量初始化要求右侧必须是编译期可直接计算的常量表达式——虽然你把IP_Options声明为const,但动态数组常量本质是运行时才分配内存的动态对象,并非真正的编译期常量,因此无法用来初始化另一个常量记录的动态数组字段。

解决办法

方法1:直接内联数组字面量

放弃单独的IP_Options常量,在记录初始化时直接写入数组内容:

type
  TParameterList = record
    Parm_Name: string;
    Parm_Unit: string;
    IsRequired: Boolean;
    Default_Value: String;
    ParmV: Integer;
    Value_Options: TArray<String>;
  end;

const
  Cables_Parms: array[0..4] of TParameterList = (
    (Parm_Name: 'Insulation'; Parm_Unit: 'N/A'; IsRequired: True; Value_Options: ['Option 1','Option 2','Option 3']),
    // 其他条目...
  );

方法2:改用静态数组(支持内容复用)

如果需要复用数组内容,把动态数组换成静态数组(值类型,可作为编译期常量):

type
  TStringOptionArray = array[0..2] of string; // 定义固定长度的静态数组类型
  TParameterList = record
    Parm_Name: string;
    Parm_Unit: string;
    IsRequired: Boolean;
    Default_Value: String;
    ParmV: Integer;
    Value_Options: TStringOptionArray; // 替换为静态数组类型
  end;

const
  IP_Options: TStringOptionArray = ['Option 1','Option 2','Option 3'];

const
  Cables_Parms: array[0..4] of TParameterList = (
    (Parm_Name: 'Insulation'; Parm_Unit: 'N/A'; IsRequired: True; Value_Options: IP_Options),
    // 其他条目...
  );

方法3:运行时初始化(保留动态数组)

如果必须使用动态数组且需要复用内容,放弃const声明,改为在单元的initialization段初始化:

type
  TParameterList = record
    Parm_Name: string;
    Parm_Unit: string;
    IsRequired: Boolean;
    Default_Value: String;
    ParmV: Integer;
    Value_Options: TArray<String>;
  end;

var
  Cables_Parms: array[0..4] of TParameterList; // 改为var而非const
const
  IP_Options: TArray<String> = ['Option 1','Option 2','Option 3'];

initialization
  // 初始化第一个条目
  Cables_Parms[0].Parm_Name := 'Insulation';
  Cables_Parms[0].Parm_Unit := 'N/A';
  Cables_Parms[0].IsRequired := True;
  Cables_Parms[0].Value_Options := IP_Options;
  // 初始化其他条目...

内容的提问来源于stack exchange,提问作者Issam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:52:38