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

Delphi泛型变量转字符串时Variant类型输出异常如何解决

问题根因

RTTI单元的TValue.ToString方法对Variant类型的默认处理逻辑仅返回固定标识字符串(variant),不会自动读取Variant内部存储的实际值,因此无法直接实现预期转换效果。

解决方法

在泛型方法中新增Variant类型的分支判断,单独处理Variant类型的转换逻辑即可,需要额外引用System.Variants单元:

uses
  System.Rtti, System.Variants;

class function TMyTest.GetAsString<T>(const AValue : T) : string;
var
  LValue: TValue;
begin
  LValue := TValue.From<T>(AValue);
  // 判断是否为Variant类型,也可替换为 if LValue.Kind = tkVariant then
  if LValue.IsType<Variant> then
  begin
    // 提取Variant值后调用VarToStr完成转换
    Result := VarToStr(LValue.AsType<Variant>);
    Exit;
  end;
  // Integer、Double、Boolean等其余基础类型沿用原有转换逻辑
  Result := LValue.ToString;
end;

效果验证

修改后测试代码传入值为123的Variant变量时,会输出预期结果123,原有正常工作的基础类型转换逻辑不受任何影响。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:48:01